function bind(fun, scope) {
    return function(args) {
       return fun.call(scope, args);
    };
}

function AddHandler(target,eventName,handlerName,_this)
{
	if (target.addEventListener)
		target.addEventListener(eventName, bind(handlerName,_this), false);
	else if (target.attachEvent)
		target.attachEvent("on" + eventName, bind(handlerName,_this));	
}

function NformatMin(_N)
{
	var ret = _N+"";
	if (_N>=1000)
	{
		if (_N<100000)
		{
			if (_N<10000)
				ret = Math.ceil(_N/100)/10+"k";
			else
				ret = Math.ceil(_N/1000)+"k";
		}else{
			ret = Math.ceil(_N/1000000)+"m";
		}
	}
	
	return ret;	
}


//direct handlers
function AddHandlerDirect(target,eventName,handlerName)
{
	if (target.addEventListener)
		target.addEventListener(eventName,handlerName, false);
	else if (target.attachEvent)
		target.attachEvent("on" + eventName, handlerName);	
}
function removeHandlerDirect(target,eventName,handlerName)
{
	if (target.removeEventListener)
		target.removeEventListener(eventName, handlerName, false);
	else if (target.detachEvent)
		target.detachEvent("on" + eventName, handlerName);	
}

function addIntelloLink(_obj)
{
	if ((_obj.hasIntelloLinker != true) && (_obj["href"].indexOf("mailto:")==-1))
	{
		_obj.hasIntelloLinker = true;
		_obj.intelloLinker = bind(function(_e){
            log("CLICK");
			var _link = this["href"];
            var _target = this["target"];
            if ((_link.indexOf(window.location.hostname)==-1) && ((_link.indexOf("http://")>-1) || (_link.indexOf("https://")>-1)))
            {
                window.open(_link,_target);
                return cancelEvent(e);
            }


			var e = window.event? event : _e;
			var ctrlK = e.metaKey || e.ctrlKey;
			if (ctrlK)
			{
				window.open(_link,'_newtab');
				return cancelEvent(e);			
			}else{
				if (_link.length>0)
				{
					WHP.menu.htmlClick();
					WHP.controller.navigateTo(_link);
				}
				return cancelEvent(e);
			}			
		}, _obj);
		AddHandlerDirect(_obj,"click", _obj.intelloLinker);	
	}
}
function addIntelloLinks(_obj)
{
	var ahrefs = $(_obj)[0].getElementsByTagName("a");	
	for (var i=0; i<ahrefs.length; i++)
	{
		addIntelloLink(ahrefs[i]);
	}
}

function cancelEvent(e) {
	e = e || window.event;
	if (!e) return false;
	e = e.originalEvent || e;
	if (e.preventDefault) e.preventDefault();
	if (e.stopPropagation) e.stopPropagation();
	e.cancelBubble = true;
	e.returnValue = false;
	return false;
}


function validateEmail(email) {
        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email);
    }

function setAlpha(_target, _value)
{
    var val = Number(_value);
    if (isNaN(val))
        val = 0;
    val = Math.max(0, Math.min(1.0, _value));
    val = parseInt(val*100)/100;

    if (val<1.0)
        $(_target).css({ opacity : val})
    else
        $(_target).css({ opacity : ""});
}



function elementOffset(_elem)
{
    var off = $(_elem).offset();
    if (browser.ie)
    {
        off = $(_elem).position();
    }

    return off;
}


function getScrollTop()
{
    var top = $(window).scrollTop();
    if (browser.ie)
        top = $('html').scrollTop();
    return top;
}


function extend(out, src) {
    for (var property in src) {
        out[property] = src[property];
    }
    return out;
}

function create(obj1, obj2) {
    var out = {};
    out = extend(out, obj1);
    out = extend(out, obj2);
    return out;
}

function isArray(obj) {
    return obj && typeof obj == 'object' && obj.splice && obj.join;
}

function log(msg) {

	if (!browser.ie)
    {
        console.log(msg);
    }else{
        return false;
        var doc = document.getElementById("console_ie");
        if (doc)
        {
            doc.style.display = "block";
            doc.innerHTML = doc.innerHTML+"<br/>"+msg;
        }
        doc.scrollTop =  doc.scrollHeight;
    }
}


function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}


function setCookieMin(name,value,minutes) {
    if (minutes) {
        var date = new Date();
        date.setTime(date.getTime()+(minutes*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}


function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function delCookie(name) {
    setCookie(name,"",-1);
}


function setBkPosition(_elem, _x, _y)
{
	if (browser.ie)
	{
		_elem.style.backgroundPositionX =  _x+"px";
		_elem.style.backgroundPositionY =  _y+"px";
	}else{
		_elem.style.backgroundPosition =  _x+"px "+_y+"px";
	}
}



function setClass(_elem, _className) {
	$(_elem).removeClass();
	$(_elem).addClass(_className);
}


function loadScript(sScriptSrc, oCallback) {
	var oHead = document.getElementById('head')[0];
	var oScript = document.createElement('script');
	oScript.type = 'text/javascript';
	oScript.src = sScriptSrc;
	// most browsers
	oScript.onload = oCallback;
	// IE 6 & 7
	oScript.onreadystatechange = function() {
        if (this.readyState == 'complete') {
            if (oCallback)
                oCallback();
        }
	}
	oHead.appendChild(oScript);
}

function getInternetExplorerVersion()
{
  var rv = -1;
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}


function id$(_id)
{
	return document.getElementById(_id);	
}


function setButton1s1i(_elem, _class, timeOut)
{
	setButton3s1i(_elem, _class, _class+"_over", _class+"_down", timeOut);
}


function setButton3s1i(_elem, _NormalState, _OverState, _DownState, timeOut)
{
	_elem.mouseOverState = false;
	_elem.StateTimer = -1;
	setClass(_elem, _NormalState);
	AddHandler(_elem, "mouseover",function() { 
		this.mouseOverState = true; 
		if (this.StateTimer == -1)
			setClass(this, _OverState);
	},_elem);
	AddHandler(_elem, "mouseout",function() { 
		this.mouseOverState = false; 
		if (this.StateTimer == -1)
			setClass(this, _NormalState);
	},_elem);
	AddHandler(_elem, "mousedown",function() { 
		setClass(this, _DownState);
		if (this.StateTimer != -1)
			clearInterval(this.StateTimer);	
		this.StateTimer = setInterval( bind( function(){	
			clearInterval(this.StateTimer);
			this.StateTimer = -1;
			if (this.mouseOverState)
				setClass(this, _OverState);
			else
				setClass(this, _NormalState);
		}, this), timeOut);
	},_elem);
}


function getcurPageId()
{
    var retVal = "";
    if ((new String(document.location.hash)).length>0)
    {
        retVal = getLinkNormolizedHash();
        if (typeof(retVal) == "undefined")
            retVal = "";

        if (retVal.indexOf("/")==retVal.length-1)
            retVal = retVal.substring(0, retVal.length-1);
    }else{
        retVal = getLinkNormolized();
    }
    return retVal;
}



function getLinkNormolizedHash()
{
	var hashLink = new String(document.location.hash);
    if ((hashLink.charAt(hashLink.length-1)!="/") && (hashLink.length>0))
        hashLink = hashLink+"/";

	while(hashLink.charAt(0) == "#")
		hashLink = hashLink.substring(1,hashLink.length);				
	while(hashLink.charAt(0) == "/")
		hashLink = hashLink.substring(1,hashLink.length);
		
	return hashLink;
}
function request(paras)
{ 
	var url = location.href; 
	var paraString = url.substring(url.indexOf("?")+1,url.length).split("&"); 
	var paraObj = {} 
	for (i=0; j=paraString[i]; i++){ 
	paraObj[j.substring(0,j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=")+1,j.length); 
	} 
	var returnValue = paraObj[paras.toLowerCase()]; 
	if(typeof(returnValue)=="undefined"){ 
	return "404"; 
	}else{ 
	return returnValue; 
	} 
}
function getLinkNormolized()
{
	hashLink = request('c');
	return hashLink;
}
/*
function getLinkNormolized()
{
	var hashLink = new String(document.location) ;
	hashLink = hashLink.replace(WHP.domain, "");
	hashLink = hashLink.replace("http://", "");
    hashLink = hashLink.replace("https://", "");
    if (hashLink.indexOf("//")==0)
        hashLink = hashLink.replace("//", "");
	
	while(hashLink.charAt(0) == "#")
		hashLink = hashLink.substring(1,hashLink.length);				
	while(hashLink.charAt(0) == "/")
		hashLink = hashLink.substring(1,hashLink.length);
	return hashLink;
}
*/
function normolizeLink(_str)
{
	var nStr = new String(_str);
    if (browser.ie)
    {
        nStr = nStr.substring(nStr.indexOf("#"), nStr.length);
    }
	while(nStr.charAt(0) == "#")
		nStr = nStr.substring(1,nStr.length);				
	while(nStr.charAt(0) == "/")
		nStr = nStr.substring(1,nStr.length);	
	return nStr;
}


var globalSetLinksN = 0;

function setLink(_link, _restoreState)
{
	globalSetLinksN++;
	var hashLink = _link.replace(WHP.domain, "");
	hashLink = hashLink.replace("http://", "");
    hashLink = hashLink.replace("https://", "");
	hashLink = hashLink.replace("https://", "");
    if (hashLink.indexOf("//")==0)
        hashLink = hashLink.replace("//", "");
	hashLink = hashLink.replace("/", "?c=");
	//visualize link change
	if (browser.ie)
	{
		curUrl = hashLink;
		document.location.hash = hashLink;
	}else{
		
		var stateObj = { curLink: hashLink };

        if (_restoreState)
            window.history.replaceState(_restoreState, document.title, document.location);
		//return false;
		window.history.pushState(stateObj, document.title, hashLink);
	}
    var restparams = null;
    if (WHP.controller.curPage)
        restparams = WHP.controller.curPage.restoreParams;

    var histObj = { url : getcurPageId(), object : restparams };
	WHP.controller.history.push(histObj);
	WHP.curHash = new String(document.location.hash);
    
	WHP.stats.trackPageChange(getcurPageId());
}

function setLinkReplace(_link, _restoreState)
{
	globalSetLinksN++;
    var hashLink = _link.replace(WHP.domain, "");
    hashLink = hashLink.replace("http://", "");
    hashLink = hashLink.replace("https://", "");
    if (hashLink.indexOf("//")==0)
        hashLink = hashLink.replace("//", "");
	hashLink = hashLink.replace("/", "?c=");
    //visualize link change
    if (browser.ie)
    {
        curUrl = hashLink;
        document.location.hash = hashLink;
    }else{
        var stateObj = { curLink: hashLink };

        window.history.replaceState(_restoreState, document.title, hashLink);
    }
    WHP.curHash = new String(document.location.hash);


    WHP.stats.trackPageChange(hashLink);
}



function getDateDelt(_date){
	var incomingDate = new Date(_date);
	today = new Date();
	
	var delta = today-incomingDate;

    var preStr = "";
    if (delta<0)
    {
        preStr = "timemachine invented ";
        delta = -delta;
        log("timemachine invented!");
    }
	
	var yD = parseInt(delta / 1000 / 60 / 60/ 24 / 365 );
	var dD = parseInt(delta / 1000 / 60 / 60/ 24 );
	var hD = parseInt(delta / 1000 / 60/ 60 );
	var mD = parseInt(delta / 1000 / 60 );
	var sD = parseInt(delta / 1000 );
	
	
	if (sD<60)
	{
		if (sD==1)
			return "1 second"
		else
			return preStr+sD+" seconds";
	}else if (mD<60)
	{
		if (mD==1)
			return preStr+"1 minute"
		else
			return preStr+mD+" minutes";
	}else if (hD<24)
	{
		if (hD==1)
			return preStr+"1 hour"
		else
			return preStr+hD+" hours";
	}else if (dD<365)
	{
		if (dD==1)
			return preStr+"1 day"
		else
			return preStr+dD+" days";
	}else{
		if (yD==1)
			return preStr+"1 year"
		else
			return preStr+yD+" years";
	}
	
	return preStr+"once upon a time";
}



function getTimeFormatedTl(_date){
	var incomingDate = new Date(_date);
	today = new Date();
	
	var delta = today-incomingDate;
	
	var yD = parseInt(delta / 1000 / 60 / 60/ 24 / 365 );
	var dD = parseInt(delta / 1000 / 60 / 60/ 24 );
	var hD = parseInt(delta / 1000 / 60/ 60 );
	var mD = parseInt(delta / 1000 / 60 );
	var sD = parseInt(delta / 1000 );
	
	
	if (sD<60)
	{
		return "< 1m";
	}else if (mD<60)
	{
		return mD+"m";
	}else if (hD<24)
	{
		return hD+"h";
	}else if (dD<365)
	{
		return dD+"d";
	}else{
		return yD+"y";
	}
	
	return "long time";
}



function getTimeFormated(_date){
	var incomingDate = new Date(_date);
	today = new Date();
	
	var delta = today-incomingDate;
	
	var yD = parseInt(delta / 1000 / 60 / 60/ 24 / 365 );
	var dD = parseInt(delta / 1000 / 60 / 60/ 24 );
	var hD = parseInt(delta / 1000 / 60/ 60 );
	var mD = parseInt(delta / 1000 / 60 );
	var sD = parseInt(delta / 1000 );
	
	
	if (sD<60)
	{
		return "< 1 m";
	}else if (mD<60)
	{
		return mD+" m";
	}else if (hD<24)
	{
		return hD+" h";
	}else if (dD<365)
	{
		return dD+" d";
	}else{
		return yD+" y";
	}
	
	return ">>";
}

function messageCheckSPaces(s) {
	s = s.replace(/(^\s*)|(\s*$)/gi,"");
	s = s.replace(/(^\n*)|(\n*$)/gi,"");
	s = s.replace(/[ ]{2,}/gi," ");
	s = s.replace(/\n /,"\n");
	return s;
}

function checkInputEmpty(_str)
{
	var has = true;
	var str = _str;
	str = messageCheckSPaces(_str);	
	if (str.length==0)
		has = false;
	return has;
}

function openWindow2(_name, _w, _h)
{
    if (browser.ie)
        var wind = window.open(_name)
    else
        var wind = window.open(null, _name, "width="+_w+",height="+_h);
    var screenW = screen.width;
    var screenH = screen.height;
    if (wind)
        wind.moveTo((screenW-_w)*0.5, (screenH-_h)*0.5);

    return wind;
}

function getTextCutted(_str, _len)
{
	var startStr = messageCheckSPaces(_str);
	var strLen = startStr.length;
	var endStr = " ...";
	
	if (strLen>=_len-1-endStr.length)
	{
		var endStr = "...";
		var comm = startStr.substring(0,_len-1-endStr.length);
		comm = comm.substring(0, comm.lastIndexOf(" "));
		
		while ((comm.charAt(comm.length-1)== " ") || (comm.charAt(comm.length-1)== "\n"))
			comm = comm.comm.substring(0, comm.length-1);
			
		if (comm.length==0)
		{
			comm = startStr.substring(0,_len-1-endStr.length) + endStr;
		}else{
			comm = comm + endStr;
		}
	}else{
		var comm = startStr;
	}
	return comm;
}

function getNameCutted(_str, _len)
{
	var endStr = "...";
	if (_str.length > _len-1-endStr.length)
	{
		var comm = _str.substring(0,_len-1-endStr.length)+endStr;
	}else{
		var comm = _str;
	}
	return comm;	
}

function setDocTitle(_str)
{
	document.title = _str;
}

function setFCK_FF_BKy(_elem, _Y)
{
    if (browser.firefox || browser.opera)
    {
        var pos = [];
        pos = $(_elem).css('background-position').split(" ");
        if ((typeof(pos[0]) == 'undefined') || (pos[0] == ""))
            pos[0] = "0px";

        if ((typeof(pos[1]) == 'undefined') || (pos[1] == ""))
            pos[1] = "0px";

        $(_elem).css({ 'background-position' : pos[0]+" "+_Y + 'px' });
    }else{
        $(_elem).css({ 'background-position-y' : _Y + 'px' });
    }
}
function setFCK_FF_BKx(_elem, _X)
{
    if (browser.firefox || browser.opera)
    {
        var pos = [];
        pos = $(_elem).css('background-position').split(" ");
        if ((typeof(pos[0]) == 'undefined') || (pos[0] == ""))
            pos[0] = "0px";

        if ((typeof(pos[1]) == 'undefined') || (pos[1] == ""))
            pos[1] = "0px";

        $(_elem).css({ 'background-position' : _X + 'px '+pos[1] });
    }else{
        $(_elem).css({ 'background-position-x' : _X + 'px' });
    }
}


function getTrimmedTextToSize(_str, _fSize, _w, _bold)
{
	var str = _str;
	var canvas = $("#service_layer");
	canvas.css({ 'font-size' : _fSize });
	if (_bold)
	{
		canvas.css({ 'font-weight' : 'bold' });
	}else{
		canvas.css({ 'font-weight' : 'normal' });
	}
	canvas.text(str);
	
	var fW = canvas.width()+1;
	if (fW>_w)
	{
		str = str.substring(0, str.length-3);
		canvas.text(str);
	}

	while ((str.length>0) && (canvas.width()+1>_w))
	{
		str = str.substring(0, str.length-1);
		canvas.text(str);
	}
	
	if (_str.length!=str.length)
		str = str+"...";

	return str;
}

function getILimit(offset,total,deltN, maxCount)
{
	var count = total-offset;
	count = Math.max(count, maxCount);
	if (count > maxCount+deltN)
		count = maxCount;
	return count;
}



function limitPos(_pos, _len)
{
    var nP = _pos;

    if (nP>=_len)
        nP = nP % _len;

    if (nP<0)
        nP = _len-(-nP % _len);

    return nP;
}

function printNotify19(_N, _cont)
{
	var N = parseInt(_N);
	if (isNaN(N))
		N = 0;
	if (N>999)
		N = 999;
	N = N+"";
	if (N.length<2)
		N = "0"+N;
	
	
	for (var i=0; i <N.length; i++)
	{
		var elem = document.createElement("div");
		elem.title = N;
		setClass(elem, "events_font_19");
		elem = $(elem);
		elem.css({'background-position-x' : -parseInt(N.charAt(i))*19+'px'});
		$(_cont).append(elem);
	}
	$(_cont).css({ width : N.length*19+2+'px'});
	return N.length;
}


Switcher = function (_object) { return {
        object : _object,

        setView : function(_state)
        {
            if (_state)
            {
                setClass(_object, "settings_switcher_1");
            }else{
                setClass(_object, "settings_switcher_0");
            }
        }
    }
}

InputMasked = function (_object, _text) { return {
    object : _object,
    onBlur : null,
    onFocus : null,
    onInput : null,

    maskedText : _text,

    init : function()
    {
        object.focus(bind(this._onFocus, _elem));
        object.blur(bind(this._onBlur, _elem));
        if (this.onInput)
            object.keyup(bind(this.onInput, _elem));
    },

    onFocus : function(e)
    {

        if (this.onFocus)
            this.onFocus(e);
    },

    onBlur : function(e)
    {
        if (this.onBlur)
            this.onBlur(e);
    }
}
}

			
			
Timer = function (_delay, _count) { return {
	timerId : -1,
	currentCount : 0,
	repeatCount : Math.max(0,_count),
	//0 - till an infinity exists
	delay : Math.max(1,_delay),
	active : false,
	
	onTimerEvent : null,
	onTimerEventEnd : null,
	
	
	start : function ()
	{
		if (this.active)
			return false;
		
		if (!this.onTimerEvent && !this.onTimerEventEnd)
			return false;
		
		this.active = true;
		
		if ((this.currentCount <= this.repeatCount) || (this.repeatCount == 0))
			this.timerId = setInterval(bind(this.timerProgress, this), this.delay);
	},
	stop : function()
	{
		if (this.timerId!=-1)
			clearInterval(this.timerId);
		this.timerId = -1;
		this.active = false;
	},
	
	reset : function()
	{
		this.stop();
		this.currentCount = 0;
	},
	
	timerProgress : function()
	{
		
			
		if ((this.currentCount >= this.repeatCount) && (this.repeatCount > 0))
		{
			clearInterval(this.timerId);
			this.currentCount = this.repeatCount;
			this.timerId = -1;
			this.active = false;
			
			if (this.onTimerEventEnd)
			{
				var timerEvent = {type : "onTimerEventEnd", currentCount : this.currentCount, repeatCount : this.repeatCount, target : this};
				this.onTimerEventEnd(timerEvent);
			}
		}
		
		if (this.onTimerEvent)
		{
			var timerEvent = {type : "onTimerEvent", currentCount : this.currentCount, repeatCount : this.repeatCount, target : this};
			this.onTimerEvent(timerEvent);
		}
		
		this.currentCount++;
	}
}}

function getObjectJson(_resp)
{
	var out = _resp;
	if (typeof(out) != 'object')
		out = $.parseJSON(_resp);
	return out;
}


function setOnLoadIMG(_src, _func)
{
    var nScr = _src;
    var img = new Image();
    img.whp_complete = false;
    $(img).load(bind(function() {
        if (this.whp_complete)
        {
            log("1 img fired from cache FALSE");
            return false;
        }
        if (_func)
            _func();
    }, img));
    img.src = nScr;
    if (img.complete)
    {
        log("COMPLETE EXCACTLY!");
        img.whp_complete = true;
        if (_func)
            _func();
    }
}


function setOnLoad(_img, _src, _loaderbk, _func)
	{
		var nScr = _src;
		var img = new Image();
        img.whp_complete = false;
		$(img).load(bind(function() {
            if (this.whp_complete)
            {
                log("2 img fired from cache FALSE");
                return false;
            }


			$(_img).attr('src', nScr);
            $(_img).css({visibility: 'visible'});

			if (_loaderbk)
				$(_loaderbk).css({ 'background-image' : 'none' });
            if (_func)
                _func();
		}, img));
		img.src = nScr;

		if (img.complete)
		{
            img.whp_complete = true;
            $(_img).attr('src', nScr);
            $(_img).css({visibility: 'visible'});

			if (_loaderbk)
				$(_loaderbk).css({ 'background-image' : 'none' });
            if (_func)
                _func();
		}else{
			$(_img).css({visibility: 'hidden'});
		}
	}

function onLoadTimerEvent(e)
{
    var A =  e.currentCount/e.repeatCount;

    setAlpha(this, A);
}






function setImageOnload(_img, _src, _loaderbk, _func)
{

    var nScr = _src;
    var img = _img.get()[0];
    img.whp_complete = false;
    img.onLoadTimer = new Timer(1000/30, 4);

    img.onLoadTimerEvent = bind(onLoadTimerEvent, img);
    img.onLoadTimer.onTimerEvent = img.onLoadTimerEvent;


    var func = bind(function() {
        if (this.whp_complete)
        {
            //log("CANCELED!");
            return false;
        }
        this.whp_complete = true;

        if (browser.ie)
        {
            $(_img).css({visibility: 'visible'});
        }else{
            setAlpha(_img, 0.0);
            $(_img).css({visibility: 'visible'});
            this.onLoadTimer.reset();
            this.onLoadTimer.start();
        }



        if (_loaderbk)
            $(_loaderbk).css({ 'background-image' : 'none' });
        if (_func)
            _func();
    }, img);

    $(img).load( func );
    img.src = nScr;

    if (img.complete)
    {
        //log("FROM CACHE = ["+_src+"]");
        func();
    }else{
        $(_img).css({visibility: 'hidden'});
    }
}




function checkBoxClick(e)
{
    this.checkedBox = !this.checkedBox;
    this.removeClass();
    if (this.checkedBox)
    {
        this.addClass("gui_checkmark_1");
    }else{
        this.addClass("gui_checkmark_0");
    }

    if (this.actionsFunc)
    {
        this.actionsFunc(this.checkedBox);
    }
}

function setCheckBox(_elem, func,  _label)
{
    var elem = $(_elem);
    if (elem.hasClass("gui_checkmark_0"))
    {
        elem.checkedBox = false;
    }else{
        elem.checkedBox = true;
    }
    elem.actionsFunc = func;

    elem.click(bind(checkBoxClick, elem));
    if (_label)
        _label.click(bind(checkBoxClick, elem));

}


function checkIfAnalyticsLoaded() {
    if (window.gat_ && window.gat_.getTracker_) {
        // Do tracking with new-style analytics
        return true;
    } else if (window.urchinTracker) {
        // Do tracking with old-style analytics
        return true;
    }
    return false;
}


(function($){

    var url1 = /(^|&lt;|\s)(www\..+?\..+?)(\s|&gt;|$)/g,
        url2 = /((^|&lt;|\s)*(\b(https?|ftp)):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@\/%~_|])/ig,
        url3 = /([^|a-z0-9])@([A-Za-z0-9_]+)/ig ,

        linkifyThis = function () {
            var childNodes = this.childNodes,
                i = childNodes.length;
            while(i--)
            {
                var n = childNodes[i];
                if (n.nodeType == 3) {
                    var html = $.trim(n.nodeValue);
                    if (html)
                    {
                        html = html.replace(/&/g, '&amp;')
                            .replace(/</g, '&lt;')
                            .replace(/>/g, '&gt;')
                            .replace(url2, function($1){
                                var str = $1;
                                str = str.replace("http://","");
                                str = str.replace("https://","");
                                str = str.replace("mailto://", "");

                                return '<a class="comment_link_text" href="'+$1+'">'+str+'</a>';
                            })
                            .replace(url1, '$1<a class="comment_link_text" href="http://$2">$2</a>$3')
                            .replace(url3, '$1<a class="comment_link_text" href="http://twitter.com/$2">@$2</a>');

                        $(n).after(html).remove();
                    }
                }
                else if (n.nodeType == 1  &&  !/^(a|button|textarea)$/i.test(n.tagName)) {
                    linkifyThis.call(n);
                }
            }
        };

    $.fn.linkify = function () {
        return this.each(linkifyThis);
    };

})(jQuery);

// Usage example:


var browser = {
	ie6: !window.XMLHttpRequest,
    ie: navigator.userAgent.indexOf('MSIE') > -1,
    ie_version : getInternetExplorerVersion(),
    opera: navigator.userAgent.indexOf('Opera') > -1,
    safari: navigator.userAgent.indexOf('Safari') > -1,
    firefox: navigator.userAgent.indexOf('Firefox') > -1,
	chrome: navigator.userAgent.indexOf('Chrome') > -1,
	
	mac: navigator.platform.indexOf('Mac') > -1,
	win: navigator.platform.indexOf('Win') > -1,
	linux: navigator.platform.indexOf('Linux') > -1,

    iphone: navigator.platform.indexOf('iPhone') > -1,
    android: navigator.userAgent.indexOf('Android') > -1,
    ipad: navigator.platform.indexOf('iPad') > -1,
    wmobile : ((navigator.userAgent.indexOf('Windows CE')>-1) || (navigator.userAgent.indexOf('Windows Mobile')>-1) || (navigator.userAgent.indexOf('Windows Phone')>-1)),
    symbian : navigator.userAgent.indexOf('Symbian') > -1
}


WHP = {
	inited : false,
	netTimeOut : 30000,
    errorMessTO : 4000,
	curUrl : "",
	curHash : "",
	domain : "",
	templateContId : "templates",
	canvasContId : "content",
    contentCont : null,




    footer : null,
    footer_dummy : null,
    main_fader : null,
	
	//vars for screen
	screenWLimit : 1000,
	screenHLimit : 512,
	screenW : 0,
	screenH : 0,
	screenWl : 0,
	screenHl : 0,
	
	scrollsWidth : 27,
	mainObject : null,
	
	pageTitle : "WeHeartPics",
	docTitle : "",
	
	totalH : 0,
	totalW : 0,

    liked1 : false,

    apple_store_link : "http://itunes.apple.com/app/weheartpics/id488515478?mt=8",


    changeContentEventTimer : new Timer(1000/20,0),

    changeContentEventLastH : 0,
    changeContentEventLastH2 : 0,
    changeContentEventLastH3 : 0,


    shadows : {
        tile : null,
        vtop : null
    },


    shares : {
        visible : true,
        container : null,
        parent : null,


        promoteButton : null,
        normalButton : null,
        promoteImg : null,

        promoteFirst : false,

        init : function()
        {
            this.promoteFirst = (getCookie("fsp") == "true");

            //this.container
            this.normalButton = $(this.parent.footer).find(".landing_facebook_lk");
            this.promoteButton = $(this.parent.footer).find(".landing_promote");
            this.promoteButton.likeholder = this.promoteButton.find(".like_holder");
            this.promoteImg = $(this.parent.footer).find(".landin_knight2");

            this.setMissed( $(this.parent.footer).find(".landing_share_fb"), $($(this.parent.footer).find(".missed_labl1")[0]) );
            this.setMissed( $(this.parent.footer).find(".landing_share_tw"), $($(this.parent.footer).find(".missed_labl1")[1]) );
            this.setMissed( $(this.parent.footer).find(".landing_share_fb2"), $($(this.parent.footer).find(".missed_labl2")[0]) );
        },

        showAct2 : function()
        {
            this.promoteButton.css({ display: ''});
            this.promoteImg.css({ display: ''});
        },
        hideAct2 : function()
        {
            if (this.promoteFirst)
            {
                this.normalButton.css({ display : 'none' });
                this.promoteButton.css({ display: '' });
            }else{
                this.normalButton.css({ display : '' });
                this.promoteButton.css({ display: 'none' });
            }

            if (typeof(FB)!='undefined')
            {
                var likeButtonStr = '<div style="position: absolute; top:6px;left:8px; height:20px;" class="fb-like" data-href="http://ituhe.com/" data-send="false" data-layout="button_count" data-width="90" data-height="20" data-show-faces="false" action="recommend"></div>';

                //this.shares.promoteButton.likeholder.html("");
                this.promoteButton.likeholder.html(likeButtonStr);
                FB.XFBML.parse(this.promoteButton.likeholder.get()[0]);
            }


            this.promoteImg.css({ display: 'none' });
            this.parent.footer.css({ height : 61+'px'});
            WHP.resetH();
        },

        changeFooterH : function()
        {
            if (this.parent)
            {
                //this.parent.resize();
            }
        },

        onFbLike : function(e)
        {
            if (this.visible)
            {
                if ((e == "http://ituhe.com/") || (e == "https://ituhe.com/"))
                {
                    log("!!!!");

                    if (browser.ie)
                    if ( this.liked1 )
                        this.parent.footer.css({ height : 350+'px'});

                    this.parent.footer.css({ height : 270+'px'});

                    this.changeFooterH();
                }else{
                    this.liked1 = true;
                    setCookie("fsp", "true", 365*24);
                    var a = this.promoteButton.find(".missed_labl2");
                    setClass(a, "missed_labl1");
                    a.css({ left : -134+"px"});

                    this.parent.footer.css({ height : 150+'px'});
                    this.promoteFirst = true;
                    this.showAct2();
                }
                var posTo = $(document).height() - WHP.screenHl;
                WHP.smoothScrollTo(0, posTo, null, true);
                return true;
            }
            return false;
        },
        setMissed : function(elem, missed)
        {
            elem.click(bind(function(){ this.missed.css({ display: 'block' }); this.timer.reset(); this.timer.start(); }, elem));
            elem.timer = new Timer(1500,1);
            elem.timer.onTimerEvent = bind(function(e){  this.missed.css({ display: 'none'}) }, elem);
            elem.missed = missed;
        }
    },




    smoothScrollParams : {
        timer : new Timer(1000/32, 10),
        p0 : { x: 0, y: 0},
        p1 : { x: 0, y: 0},

        onMoveEnd : null,
        onMoveFrame : null
    },

	
	onLoad: function (e)
	{

        //detect
        this.detectSocialRedirects();
        //this.detectMobileRedirects();


		this.init();		
	},

    detectMobileRedirects : function()
    {
        alert(navigator.userAgent);
        alert(navigator.platform);
        alert(navigator.appName);

        // Detects if it is an Android device
        if (browser.iphone)
        {
            alert("IPHONAMA");
        }else if (browser.android)
        {
            alert("ANDROIDAMA");
        }else if (browser.wmobile)
        {
            alert("WINDOWSMOBILAMA!");
        }else if (browser.symbian)
        {
            alert("SYMBIANOMA!");
        }
    },

    detectSocialRedirects : function()
    {
        //detect redirects\
        //facebookredirect
        if (String(document.location).indexOf("fb_xd_fragment")>-1)
        {
            window.close();
        }

        //ie has redirect V
        var urla = "";
        var hashLink = getLinkNormolizedHash();
        if (hashLink.length==0)
            urla = getLinkNormolized();
        else
            urla = hashLink;

        //remove special symbols
        if (urla.indexOf("?")>-1)
            urla = urla.substring(0, urla.indexOf("?"));
        urla = urla.replace(new String(window.location.hostname), "");

        while (urla.charAt(0) == "/")
            urla = urla.substring(1, urla.length);

        if (document.location.hash.length>0)
        if (browser.ie)
        {
            document.location = "//" + new String(window.location.hostname) + "/" + urla;
            return false;
        }
    },

	resize: function (e)
	{
        var newW = $(window).width();
		var newH = $(window).height();
		//get zoom changed
		var kX = this.screenW/newW;
		var kY = this.screenH/newH;
		//log("Screen kX = ["+kX+"] ["+kY+"] delt = ["+(kX-kY)+"]");
		if (Math.abs(kY-kX)<0.05)
		{
			//log("zoom Changed");
		}


        if (WHP.controller.curPage)
        if (WHP.controller.curPage.onResizeEvent)
        {
            var e = { type : "onResizeEvent", newHeight : newH, newWidth : newW };
            WHP.controller.curPage.onResizeEvent(e);
        }

		//get viewport size
		this.screenW = newW;
		this.screenWl = Math.max(newW, this.screenWLimit);
		this.screenH = newH;
        if (browser.ie)
        {
            this.screenHl = Math.max(newH, this.screenHLimit-4);
        }else{
            this.screenHl = Math.max(newH, this.screenHLimit);
        }




        if (WHP.controller.curPage)
        if (WHP.controller.curPage.onResizeEvent)
        {
            var e = { type : "onResizeEvent", newHeight : newH, lastHeight : this.changeContentEventLastH, delt : (newH - this.changeContentEventLastH)};
            WHP.controller.curPage.onResizeEvent(e);
        }

        // log("["+this.screenWl+"]x["+this.screenHl+"]");
		this.mainObject.style.width = this.screenWl - this.scrollsWidth +'px';
		WHP.menu.menuObject.css({ width : (this.screenWl - this.scrollsWidth)+'px'});


        this.main_fader.css({width:this.screenWl+'px', height:this.screenHl+'px'});

        this.resetH();
	},


    getViewportParams : function()
    {
        var newW = $(window).width();
        var newH = $(window).height();
        //get zoom changed
        var kX = this.screenW/newW;
        var kY = this.screenH/newH;
        var kY = this.screenH/newH;

        this.screenW = newW;
        this.screenWl = Math.max(newW, this.screenWLimit);
        this.screenH = newH;
        this.screenHl = Math.max(newH, this.screenHLimit);
    },



	resetHtimeout: 0,
	resetH: function (e)
	{
        return false;
	},



    changeContentH : function(e, _force)
    {
        return false;
    },


	init: function ()
	{
		this.mainObject = id$('main_object');

        //shadows
        this.shadows.tile = $("#border_vtile");
        this.shadows.vtop = $("#border_top");

        //foooooter
        this.footer = $("#footer1");
        this.footer_dummy = $("#footer_dummy");
        var links = this.footer.find(".footer_link");
        for (var i = 0 ; i<links.lenght; i++)
        {
            links[i].hasIntelloLinker = true;
        }
        this.shares.parent = this;
        this.shares.init();

        this.main_fader = $("#main_fader");
        setAlpha(this.main_fader, 0);
        this.main_fader.css({ display : 'none'});
        this.main_fader.timer = new Timer(1000/30,5);
        this.main_fader.timer.onTimerEvent = bind(this.faderFunc, this.main_fader);
        this.main_fader.show = bind(this.showFader, this.main_fader);
        this.main_fader.hide = bind(this.hideFader, this.main_fader);
        this.main_fader.click(bind(this.faderClick, this));
        this.main_fader.p0 = 0;
        this.main_fader.p1 = 0;
        this.main_fader.cP = 0;


        this.contentCont = $("#content");
        //this.scrollsWidth = getScrollBarWidth();
		
	//	this.resize();
		this.domain = window.location.hostname;
		//init all links
		this.initCalls();
		
		AddHandler(window, "resize", this.resize, this);
		//init modules
        WHP.serviceMessages.init();
        WHP.timelineMessages.init();
        WHP.stats.init();
		WHP.menu.init();
		WHP.notifications.init();
        WHP.download.init();
		WHP.auth.init();
        WHP.popup_message.init();



        this.smoothScrollParams.timer.onTimerEvent = bind(this.smoothScrollEventFunc, this);
        this.changeContentEventTimer.onTimerEvent = bind(this.changeContentH, this);
		this.changeContentEventTimer.start();


        var mousewheelevt = browser.firefox ? "DOMMouseScroll" : "mousewheel";
        AddHandler(document, mousewheelevt, bind(this.mwheelEvent,this));
        $(window).scroll(bind(this.scrollEvent,this));







		this.inited = true;
	},
	
	initCalls : function ()
	{
		for (var key in this.netcalls)
		{
			this.netcalls[key] = this.netcalls[key];
		}
	},
	
	netcalls: {
		//timeline
		timelineCallUrl : "api/user/timeline",
        timelineGlobalCallUrl : "api/timeline",
		
		//comments calls
		commentsCallAdd : "api/photo/comment/add",
        commentsCallReply : "api/photo/comment/reply",

		commentsCallGet : "api/photo/comments",

		//auth
		logoutCall : "api/auth/logout",
		checkAuthCall : "api/auth/me",


        userPhotosCall : "api/user/storyphotos",


		//stories
		catTreeCall : "api/story/storysets",
        dailyStories : "api/story/daily/list",
		
		//user
		getProfileCall : "api/user",

        //stories
        storyInfoUrl : "api/story/info",
        storiesCall : "api/story/tree",

        //likes
        likesCall : "api/photo/likes",
        voteCall : "api/photo/vote",



        //friends calls
		followCall : "api/friends/follow",
		unfollowCall : "api/friends/unfollow",
        shiftBkCall : "api/profile/shiftbackground",
        newFacesCall : "api/friends/newfaces",

		followersCall : "api/friends/followers",
		followingsCall : "api/friends/followings",


		
		//random
		randomImageCall : "api/photo/random",


		//scenario
		wasVoteCall : "api/photo/checkvote",

		//popular
		popularCall : "api/photo/popular",
		
		//photo
		photoInfoCall : "api/photo",
		
		//notifications
		eventsCall : "api/getevent",
        eventsCountCall : "api/event/count",
		clearCall : "api/clearevents",
		lpCall : "notify",

		//auth
		fbAuthCall : "api/auth",
		twReqTokenCall : "api/auth/twitter/request_token",
		
		//user timeline
		storiesUserCall : "api/user/photos",

        //promo
        promoCall : "api/promo",

        //versions
        versionCall : "api/version",

        //photo delete
        deletePhotoCall : "api/photo/delete",

        shareCallSvr : 'api/photo/share',

        getSettingsCall : 'api/user/settings',
        setSettingsCall : 'api/user/settings/set',

        regCall : "api/auth/signup",
        resendCall : "api/auth/resend_confirmation",
        resetPwCall : "api/auth/reset_passw",
        linkSocialCall : "api/auth/link",
        unlinkSocialCall : "api/auth/unlink",
        mailLoginCall : "api/auth/signin",
        setPwCall : "api/auth/change_passw",

        setLogPwCall : "api/auth/set_login_passw",
        setPwSettingsCall : "api/auth/reset_passw",

        changeLoginCall : "api/auth/change_login",
        confirmPwCall : "api/auth/check_passw",
        setNameCall : "api/user/rename"

	},



    smoothScrollEventFunc: function(e)
    {
        var A = e.currentCount/e.repeatCount;
        var dL = Math.abs(this.smoothScrollParams.p0.y - this.smoothScrollParams.p1.y);
        var B = (Math.sin(Math.PI*(A-0.5))+1)*0.5;

        var scrollX = (1-B)*this.smoothScrollParams.p0.x + B*this.smoothScrollParams.p1.x;
        var scrollY = (1-B)*this.smoothScrollParams.p0.y + B*this.smoothScrollParams.p1.y;


        WHP.menu.setShadow(scrollY);
        window.scrollTo(scrollX,scrollY);

        if (A==1)
        {
            if (this.smoothScrollParams.onMoveEnd)
                this.smoothScrollParams.onMoveEnd();
        }
    },

    smoothScrollTo: function (_x,_y, _func, _Notlimit)
    {
        this.smoothScrollParams.p0.x = $(window).scrollLeft();
        this.smoothScrollParams.p0.y = getScrollTop();


        this.smoothScrollParams.p1.x = _x;

        if (!_Notlimit)
        {
            this.smoothScrollParams.p1.y = Math.max(0, Math.min($(document).height() - WHP.screenHl, _y));
        }else{
            this.smoothScrollParams.p1.y = _y;
        }

        this.smoothScrollParams.onMoveEnd = _func;

        this.smoothScrollParams.timer.reset();

        this.smoothScrollParams.timer.repeatCount = 10 + Math.abs(this.smoothScrollParams.p0.y-this.smoothScrollParams.p1.y)*(1/50);
        this.smoothScrollParams.timer.start();
    },

    faderFunc : function(e)
    {
        var A = e.currentCount/e.repeatCount;
        var B = (Math.sin(Math.PI*(A-0.5))+1)*0.5;

        this.cP = this.p1*B + this.p0*(1-B);

        setAlpha(this, this.cP);

        if (A==1)
        if (this.cP == 0)
        {
           this.css({ display : 'none' });
        }
    },

    showFader : function()
    {
        log("showFader");
        this.css({ display : '' });
        this.p0 = this.cP;
        this.p1 = 0.75;
        this.timer.reset();
        this.timer.start();
    },

    hideFader : function()
    {
        log("hideFader");
        this.p0 = this.cP;
        this.p1 = 0.0;
        this.timer.reset();
        this.timer.start();
    },

    faderClick : function()
    {
        log("Make hide event");
        this.main_fader.hide();
    },


    smoothScrolllStop: function ()
    {
        this.smoothScrollParams.timer.stop();
    },

    mwheelEvent : function(e)
    {
        this.totalH = Math.max( $(document).height(), $(window).height() );

        if (this.smoothScrollParams.timer.active)
        {
            this.smoothScrolllStop();
        }

        if (this.main_fader.cP > 0)
            return cancelEvent(e);

        if (browser.ie)
        {
            if (browser.ie_version == 8)
            {
                var delt = -e.wheelDelta/120;

                var newS = delt*40 + getScrollTop();

                newS = Math.max(0, Math.min(this.totalH-this.screenH, newS));
                window.scrollTo(0, newS);
            }
        }
    },

    scrollEvent : function(e)
    {
        if (this.main_fader.cP > 0)
            return cancelEvent(e);
    },

    popup_message :  {
        box : null,
        curTimer : -1,

        init : function()
        {
            this.box = $("#popup_message");
            this.box.css({ position : 'fixed', height : 'auto' });
            var labels =  this.box.find(".form_label_sign");
            this.box.headLabel =  $(labels[0]);
            this.box.textLabel =  $(labels[1]);
            this.box.icons = this.box.find(".message_icons");
        },

        showAlert : function(_text, _head, _ico)
        {

            log("ICO = ["+_ico+"]");
            if (_ico)
            {
                setClass(this.box.icons, "message_icons");
                this.box.icons.html("<img src='"+_ico+"' />");
                this.box.textLabel.css({ "text-align" : "left"});
            }else{
                setClass(this.box.icons, "message_icons_0");
                this.box.icons.html("");
                this.box.textLabel.css({ "text-align" : "center"});
            }

            this.box.textLabel.text(_text);
            if (_head)
            {
                this.box.headLabel.text(_head);
                this.box.headLabel.css({ display : '' });
                this.box.textLabel.css({ 'margin-top' : '10px'});
            }else{
                this.box.headLabel.css({ display : 'none' });
                this.box.textLabel.css({ 'margin-top' : '26px'});
            }



            this.box.css({ display : ""});
            WHP.main_fader.show();




            var scrollTop = getScrollTop();


            if (browser.ie)
            {
                this.box.css({ position : 'absolute' });
                this.box.css({ top : (scrollTop + (WHP.screenH - this.box.outerWidth())*0.5 )+'px', left : (WHP.screenWl-this.box.outerWidth())*0.5 -20 +'px' });
            }else
                this.box.css({ top : (WHP.screenH - this.box.outerHeight())*0.5 +'px', left : (WHP.screenWl-this.box.outerWidth())*0.5 -20 +'px' });





            if (this.curTimer!=-1)
            {
                clearTimeout(this.curTimer);
            }
            this.curTimer = setTimeout(bind(function(){
                this.hideAlert();
                this.curTimer = -1;
            },this), 3000);
        },

        hideAlert : function()
        {
            if (this.box.css("display") == "none")
                return false;

            this.box.css({ display : "none" });
            WHP.main_fader.hide();
        }
    }
}

//additional modules
WHP.pages = {}
WHP.actions = {}









WHP.controller = {
	inited : false,	
	started : false,

    redirecting : false,
	pages : [],
	
	curPage : null,

	mainCanvas : null,
	errorPage : null,

    loadingBar : null,
	
	detectURLchangeTimer : new Timer(500, 0),
	history : [],
	
	visible : false,
	
	slideShadowTimer : new Timer(1000/30, 10),
	slideShadowP0 : 0,
	slideShadowP1 : 0,
	
	firstPop : true,

    afterRemoveBack : false,

    initLocation : '',


    removedList : [],
	
	reloadPage: function ()
	{
        if (browser.ie)
        {

            var hashLink = getLinkNormolizedHash();
            if (hashLink.length==0)
                urla = getLinkNormolized();
            else
                urla = hashLink;

            urla = urla.replace(WHP.domain, "");

            if (urla.indexOf("?")>-1)
                urla = urla.substring(0, urla.indexOf("?"));
            urla = urla.replace("http://"+WHP.domain+"/","");
            urla = urla.replace("https://"+WHP.domain+"/","");
            urla = urla.replace("//"+WHP.domain+"/","");
            this.navigateTo(urla);
        }else{
            var url = new String(document.location);
            url = url.replace("http://"+WHP.domain+"/","");
            url = url.replace("https://"+WHP.domain+"/","");
            url = url.replace("//"+WHP.domain+"/","");
            this.navigateTo(url);
        }
	},
	
	onChangeAuthState: function (_auth)
	{
        WHP.serviceMessages.onAuthChange(_auth);
        WHP.timelineMessages.onAuthChange(_auth);

		if (_auth)
		{
            if (this.curPage)
			{
				if (this.curPage.onAuthChange)
					this.curPage.onAuthChange(true)
				else
					this.reloadPage();
			}else{
				this.reloadPage();
			}


		}else{
            WHP.loginMenus.loginWindowWind.reset(true);
            WHP.loginMenus.loginWindowWind2.reset(true);
			this.navigateTo("/");
		}

        WHP.menu.currentMenuPos();
        this.setTitle();
	},
	
	showErrorPage: function (_message)
	{
        if (typeof(_message) != 'undefined')
        {
            this.errorPage.setView(_message);
        }else{
            this.errorPage.setView(0);
        }

		this.getPage(this.errorPage.urlStr);
	},

	navigateTo: function (_url, _doNotChangeLink, _restorePrev)
	{
		var urla = _url;
		if (typeof(urla) == 'undefined')
		{
			//hash link has a higher prioritet
			var hashLink = getLinkNormolizedHash();			
			if (hashLink.length==0)
				urla = getLinkNormolized();	
			else
				urla = hashLink;			
			
			//remove special symbols
			if (urla.indexOf("?")>-1)
				urla = urla.substring(0, urla.indexOf("?"));

            urla = urla.replace(WHP.domain, "");
				
			if (document.location.hash.length>0)
			{
				if (browser.ie)
				{
					//set redirect for ie
					if (!_doNotChangeLink)	
					if (!this.started)
                    {
						//document.location = "http://" + WHP.domain + "/" + urla;
                        //return false;
                    }
				}else{
					//change link for other browsers	
					if (!_doNotChangeLink)
						setLink( "//" + WHP.domain + "/" + urla);
				}				
			}
		}else{
            log(urla);
            urla = urla.replace("https://"+WHP.domain,"");
			urla = urla.replace("http://"+WHP.domain,"");	
			urla = urla.replace("http://weheartpics.com","");
            urla = urla.replace("//"+WHP.domain+"/","");
			//remove ?query
			if (urla.indexOf("?")>-1)
				urla = urla.substring(0, urla.indexOf("?"));

			urla = normolizeLink(urla);

            urla = urla.replace(WHP.domain, "");
			if (!_doNotChangeLink)
            {
                var histObj = { url : getcurPageId(), object : this.curPage.restoreParams };
                this.history.push(histObj);
                if (typeof(this.curPage.restoreParams) == "undefined")
                {
                    setLink( "//" + WHP.domain + "/" + urla);
                }else{
                    setLink( "//" + WHP.domain + "/" + urla, this.curPage.restoreParams);
                }
            }
		}


		//load content
		log("WHP/controller : get = ["+urla+"]");
		this.getPage(urla, _restorePrev);
	},
	
	getPage: function (_str, _restorePrev)
	{
		var normStr = _str;
		normStr = normolizeLink( normStr );
        log("GET = ["+_str+"]");
		
		var switchPage = null;
		
		//show start page with no parametres
		if (normStr.length == 0)
		{
			log("WHP/controller : redirect to main = ["+this.getMainPage().urlStr+"]");
            switchPage = this.getMainPage();

			setLink( "//" + WHP.domain + "/" + switchPage.urlStr);
		}

		if (!switchPage)
		{
			var maxLength = 0;			
			var nPage = 0;	//404
            var founded = false;
			switchPage = this.pages[nPage];
			log('switchPage:'+this.pages.length);
			for (var i=0; i<this.pages.length; i++)
			{
				log('switchPage:'+this.pages[i].urlStr);
				//maxL for maximum match strings
				var maxL = Math.min(normStr.length, this.pages[i].urlStr.length);
				//for urls like http://whp.com/controlstr
				var shortUrl = (normStr.indexOf(this.pages[i].urlStr)==0) && (maxL>maxLength) && (normStr.length == this.pages[i].urlStr.length);
				//for urls like http://whp.com/controlstr/
				var longUrl = (normStr.indexOf(this.pages[i].urlStr+"/")==0) && (maxL>maxLength);

				log('longUrl=' + longUrl);
				log('shortUrl=' + shortUrl);
				log('maxL=' + maxL);
				if (shortUrl || longUrl)
				{
					maxLength = maxL;
					nPage = i;
                    founded = true;
				}
			}

			
			var query = "";
			if (nPage != 0)
            {
				query = normStr.substring(maxLength+1, normStr.length);
            }else if (!founded){
                this.errorPage.setView(2);
            }

			switchPage = this.pages[nPage];
		}
		
		
		if (switchPage!=null)
		{
			//take off old page
			this.clearCurPage();
			//set new
			this.setPage(switchPage,true,query,_restorePrev);

            //service_messages
            WHP.serviceMessages.checkVisible();
            WHP.timelineMessages.checkVisible();
		}			
		
		WHP.curHash = new String(document.location.hash);
		return true;
	},	
	
	clearCurPage: function ()
	{
		if (this.curPage != null)
		{
			if (typeof(this.curPage.hide) != 'undefined')
            {
				this.curPage.hide();
                this.curPage.active = false;
            }
            log("clearCurPage");
            this.hideCanvas();
            if (this.curPage.mainObject.parentNode)
			{
				while(this.mainCanvas.childNodes.length>0)
					this.mainCanvas.removeChild(this.mainCanvas.childNodes[0]);
				
			}
		}
	},
	
	setPage: function (switchPage, _useQ, query, _restorePrev)
	{
        WHP.loginMenus.hideMenus();

		WHP.menu.currentMenuPos();
		//show new page
		this.curPage = switchPage;

        //
        WHP.shares.hideAct2();




        if (_useQ)
        {
            // log("Get sum = ["+(_restorePrev && (typeof(this.curPage.restore) != 'undefined'))+"] ["+typeof(this.curPage.restore)+"]");
            if (_restorePrev && (typeof(this.curPage.restore) != 'undefined'))
            {
                this.curPage.restore(query);
            }else{
                this.curPage.show(query);
            }
        }


		//set up rnd button
		if (this.curPage.rndEnable)
		{
			$(WHP.menu.randomButton).css({ display : 'block' });
		}else{
			$(WHP.menu.randomButton).css({ display : 'none' });
		}
		this.mainCanvas.appendChild(this.curPage.mainObject);

        this.curPage.active = true;
        this.setTitle();
	},
	
	detectURLchange: function ()
	{
		var newLink = new String(document.location.hash);
		if (newLink.valueOf() != WHP.curHash.valueOf())
		{
            if (this.history.length>1)
            {
                if (this.history[this.history.length-2].url == getcurPageId())
                {
                    //var histObj = { url : getcurPageId(), object : this.curPage.restoreParams}
                    //this.history.push(histObj);
                    WHP.curHash = newLink;
                    this.popState(this.history[this.history.length-2]);
                    return false;
                }
            }
			this.navigateTo();
			WHP.curHash = newLink;
		}
	},
	
	setTitle: function()
	{
		var str = this.curPage.title;		
		if (typeof(str) == 'undefined')
			str = "";
		var notifStr = WHP.notifications.newN;
		if (notifStr>0)
			notifStr = "("+notifStr+") "
		else
			notifStr = "";
			
		var preStr = notifStr+str;
		if (preStr.length>0)
			preStr = preStr + " - ";
		
		
		WHP.docTitle = preStr+WHP.pageTitle;
		setDocTitle(WHP.docTitle);
	},
	
	init: function (_settings)
	{

		if (this.inited)
			return true;

        this.initLocation = new String(document.location);
			
		this.pages.push(WHP.pages.error404);   //0
		this.pages.push(WHP.pages.photoPopular);   //1
		this.pages.push(WHP.pages.photo);   //2
		this.pages.push(WHP.pages.profile);  //3
		this.pages.push(WHP.pages.user);   //4
		this.pages.push(WHP.pages.timeline);     //5
		this.pages.push(WHP.pages.story);  //6
		this.pages.push(WHP.pages.stories);      //7
        this.pages.push(WHP.pages.landing);  //8
        this.pages.push(WHP.pages.settings);  //9
        //registration
        this.pages.push(WHP.pages.getstarted);  //10
        this.pages.push(WHP.pages.findfriends);   //11
        this.pages.push(WHP.pages.confirmation);   //12
        this.pages.push(WHP.pages.resendpw);    //13

        this.pages.push(WHP.pages.whp);    //14
        this.pages.push(WHP.pages.setpassword);    //15

		for (var i=0; i<this.pages.length; i++)
		{
            //log("urlStr = ["+this.pages[i].urlStr+"]");
			this.pages[i].init();			
		}
		this.mainCanvas = document.getElementById(WHP.canvasContId);
        this.loadingBar = $( "#loading_tab" );
		
		//set error page
		this.errorPage = this.pages[0];
		//set main page



        if (_settings)
            WHP.pages.settings.onData(_settings);

		//get start page
		this.navigateTo();
		this.started = true;		
		WHP.curHash = new String(document.location.hash);

        if (browser.ie)
        {
            this.detectURLchangeTimer.onTimerEvent = bind(this.detectURLchange, this);
            this.detectURLchangeTimer.start();
        }
		//AddHandler(window, 'popstate', this.popState, this);	
		
		//var popped = ('state' in window.history), initialURL = location.href;
		$(window).bind('popstate', bind(this.popState, this));
        $(window).bind('beforeunload', bind(this.terminateEvent, this));

        WHP.download.checkVersions();

		//slide shadow
		this.slideShadowTimer.onTimerEvent = bind(this.shadowTimerEvent, this);
		WHP.resize();
		this.inited = true;


        //ipad
        if (browser.ipad)
        {
            WHP.shadows.tile.css({ visibility: 'hidden'});
            WHP.shadows.vtop.css({ visibility: 'hidden'});
            $(WHP.menu.randomButton).css({ right : -68+'px' });
        }


	},
	
	shadowTimerEvent: function(e)
	{
		var A = e.currentCount/e.repeatCount;
		var B = Math.sin(Math.PI*0.5*A);
		var C = (1-B)*this.slideShadowP0 + B*this.slideShadowP1;
		WHP.menu.setShadowA(C);
	},
	
	setShadowAuto: function()
	{
		this.slideShadowTimer.reset();
		this.slideShadowP0 = WHP.menu.menuShadow.alpha;
		this.slideShadowP1 = 0;
		this.slideShadowTimer.start();
		//var top = $(document).scrollTop();
		//WHP.menu.setShadow(top);
	},

    terminateEvent : function(e)
    {
        if (typeof(this.curPage.hide) != 'undefined')
        {
            this.curPage.hide();
        }

        WHP.notifications.hide();
    },
	
	popState: function(e)
	{
		log("LINKS > onpopstate event = ["+document.location+"] ["+history.length+"] ["+ globalSetLinksN +"] ["+this.initLocation+"]");


        if ((globalSetLinksN == 0) && (document.location.valueOf() == this.initLocation.valueOf()))
        {
            log("INIT LOAD!");
            return false;
        }


		//var browserA = (browser.chrome || browser.safari || browser.firefox || browser.opera);
        this.firstPop = false;
		if ((!this.firstPop && !browser.ie) || browser.ie)
        {
            var mstate = null;

            if (browser.ie)
            {
                mstate = e.object;
            }else{
                mstate = e.originalEvent.state;
            }


            for (var key in mstate)
                log("mstate['"+key+"'] = ["+mstate[key]+"]");

			this.navigateTo(new String(document.location).valueOf(), true, mstate);
            WHP.controller.removedList = [];
        }


		this.firstPop = false;
        this.afterRemoveBack = false;
	},
	showCanvas: function()
	{
		if (this.visible)
			return false;
		
        log("SHOWCANVAS");
		this.visible = true;
        this.loadingBar.css({ display : 'none' });
		setClass(this.mainCanvas, "content_visible");

        WHP.footer.css({ visibility: "visible"});

        WHP.changeContentH(null, true);

		this.setShadowAuto();
        this.setTitle();
		

        WHP.serviceMessages.checkVisible();
        WHP.timelineMessages.checkVisible();
	},
	hideCanvas: function()
	{
		if (!this.visible)
			return false;
			
		this.visible = false;
        this.loadingBar.css({ display : 'block' });
		setClass(this.mainCanvas, "content_hidden");
        WHP.shares.hideAct2();

        WHP.footer.css({ visibility: "hidden"});

		//WHP.resetH();

		this.setShadowAuto();
        this.setTitle();
        log("HIDECANVAS");
	},

    getMainPage : function()
    {
        var a = this.pages[8];
        if (WHP.auth.status)
        {
            if (this.history.length>0)
            {
                a = this.pages[8];
            }else{
                a = this.pages[5];
            }
        }


        return a;
    },
	
	scrollToPos: function(_x, _y)
	{
		this.setShadowAuto();
		window.scrollTo(0,0);
	}
}

//special object for all displays


WHP.auth = {
	inited : false,	
	status : null,
	userObject : null,
	cookieExpireDate : 365,
    activeLogout : false,

    authChecker : {
        timer : new Timer(1000,0),
        parent : null,
        authStatus : false,
        initCheck : true,

        init : function()
        {
            this.timer.onTimerEvent = bind(this.eventOnTimer, this);
            this.start();
        },
        eventOnTimer : function()
        {
            var whp_uid = parseInt(getCookie("uid"));
            var whp_token = getCookie("token");
            var newStatus = true;



            if (isNaN(whp_uid))
            {
                whp_uid = -1;
                whp_token = 1;
                newStatus = false;
            }

            if (!this.initCheck)
            {
                if (this.authStatus != newStatus)
                {
                    if (newStatus)
                    {
                        //login
                        this.parent.setSession({  id: whp_uid , uid : whp_uid , token: whp_token }	);
                        this.parent.checkAuth();
                    }else{
                        //logout
                        if (!this.parent.activeLogout)
                        {
                            WHP.auth.onlogoutData({ state : "OK" });
                            WHP.loginMenus.showLoginMenu2();
                        }

                        if (this.parent.activeLogout)
                            this.parent.activeLogout = false;
                    }
                    this.authStatus = newStatus;
                }
            }else{
                this.authStatus = newStatus;
            }




            if (this.initCheck)
                this.initCheck = false;
        },
        flush : function(_id)
        {
            this.lastId = _id;
        },
        start : function()
        {
            this.timer.start();
        },
        stop : function()
        {
            this.timer.stop();
        }
    },
	
	init: function ()
	{
		var whp_uid = parseInt(getCookie("uid"));
		if (isNaN(whp_uid))
			whp_uid = -1;
		var whp_token = getCookie("token");
		if ((whp_uid==-1) || (whp_token == 'undefined'))
		{
			//log("WHP.auth : client - user didnt log in!");
			this.clearSession();
			WHP.controller.init();
		}else{			
			//log("WHP.auth : client - cookie user_id = ["+whp_uid+"] token = ["+whp_token+"]");	
			this.setSession({  id: whp_uid , uid : whp_uid , token: whp_token }	);	
			this.checkAuth();			
		}
		
		
		this.FB.init();
		this.TW.init();
        this.authChecker.init();
        this.authChecker.parent = this;
		
		this.inited = true;
	},
	//set gui etc of auth state
	checkStatus : function ()
	{
		WHP.menu.checkMenuState();
	},	
	
	//session control functions
	setUser : function (_user)
	{
		this.userObject = new Object(_user);
	},

	setSession : function (_status)
	{
		log("(!) WHP/auth : Session check for ID = ["+_status.id+"] TOKEN = ["+_status.token+"]");
			
		this.status = _status;
		
		setCookie("uid",this.status.id,this.cookieExpireDate);
		setCookie("token",this.status.token,this.cookieExpireDate);
        this.authChecker.flush(this.status.id);
	},

	clearSession : function ()
	{
		WHP.auth.status = null;
		WHP.auth.checkStatus();
		setClass(document.body, "body_main");


	},
	
	//test login state on start
	checkAuth : function()
	{
		if (this.status)
		{
			$.ajax({
				url: WHP.netcalls.checkAuthCall+"?"+Math.random(),
				timeout : WHP.netTimeOut,
				data : this.status,
				success: bind(this.oncheckAuthData, this),
				error: bind(this.oncheckAuthDataErr, this)
			});
		}
	},	
	
	onStartWork : function (resp)
	{
		WHP.auth.checkStatus();
		WHP.notifications.newN = resp.user.events;
		WHP.notifications.setNumber(resp.user.events);
		WHP.notifications.startLPTimer();
	},
	
	oncheckAuthData : function(response)
	{

		var resp = getObjectJson(response);	
		if (resp.error)
		{
            WHP.controller.init();
			//user id and token arent actal
			log("WHP/auth : check state ERROR after netcall!");
			delCookie("uid");
			delCookie("token");	
			this.checkStatus();
			this.clearSession();
		}else{
			WHP.auth.setUser(resp.user);
			WHP.auth.onStartWork(resp);
			setClass(document.body, "body_main");
            log("AUTH.oncheck");
            WHP.controller.init(resp);
            //WHP.pages.settings.onData(
		}
	},
	
	oncheckAuthDataErr : function(e)
	{
		//set up unloged
		log("WHP/auth : check state ERROR self!");
		WHP.controller.init();
		delCookie("uid");
		delCookie("token");	
		this.checkStatus();
		this.clearSession();
	},




	//logout functions
	logout : function()
	{

		if (this.status)
		{
			//log("Facebook : access_token = ["+this.FB.access_token+"]");
			this.logoutServer();
		}
	},
	logoutServer : function(response)
	{
		log("WHP/auth : logout...");
        this.activeLogout = true;
		setClass(WHP.menu.logoutButton[0], "controls_logout_button_procces");
		$.ajax({
				url: WHP.netcalls.logoutCall+"?"+Math.random(),
			 	timeout : WHP.netTimeOut,
			 	success: bind(this.onlogoutData, this),
			 	error: bind(this.onlogoutDataErr, this)
			});
	},
	onlogoutData : function(response)
	{
		var resp = getObjectJson(response);	
		if (resp.error)
		{
			log("WHP/auth : on logout error = ["+resp.error.code+"]");
			if (resp.error.code == API_Auth_Failed)
				WHP.auth.authError();
		}else{
			log("WHP/auth : response status = ["+resp.status+"]");
		}
		this.logoutCallBack();
	},
	onlogoutDataErr : function(e)
	{
		log("WHP/auth : error while logging out!");
		WHP.controller.showErrorPage();
	},
	logoutCallBack : function()
	{
		delCookie("uid");
		delCookie("token");	
		this.clearSession();
        WHP.controller.setTitle();
		WHP.controller.onChangeAuthState(null);
		WHP.notifications.onLogOut();
	},
	logoutCallBackOnerr : function()
	{
		log("WHP/auth : LOGOUT ERROR!");
		delCookie("uid");
		delCookie("token");	
		this.clearSession();
		WHP.controller.onChangeAuthState(null);
		WHP.notifications.onLogOut();
	},
	
	
	
	
	//global error
	authError : function()
	{
		log("WHP/auth : LOGOUT!");
		this.logoutOnerrorServer();
	},
	logoutOnerrorServer : function(response)
	{
		log("WHP/auth : on Err server logout...");
		$.ajax({
				url: WHP.netcalls.logoutCall+"?"+Math.random(),
			 	timeout : WHP.netTimeOut,
			 	success: bind(this.logoutCallBackOnerr, this),
			 	error: bind(this.onlogoutDataErr, this)
			});
	},





    FB : {
        inited : false,
        access_token : null,
        jqxhr : null,

        showErrMsg : null,

        init: function ()
        {
            window.fbAsyncInit = bind(function () {
                //facebook functions
                FB.init({
                    appId: '205868409437437',
                    cookie: true,
                    status: true,
                    xfbml: true,
                    oauth : false });
                FB.Event.subscribe('edge.create', this.fbShareEvents);

                if ($.browser.opera)
                {
                    FB.XD._transport="postmessage";
                    FB.XD.PostMessage.init();
                }

                FB.getLoginStatus(bind(function (response) {
                    if (response.status == "connected")
                    {
                        log("Facebook : user was succesfully connected! :)");
                    }else{
                        log("Facebook : user was not connected! :(");
                    }
                }, this));

            }, this);

            //load facebook module
            (function(d, s, id) {
              var js, fjs = d.getElementsByTagName(s)[0];
              if (d.getElementById(id)) {return;}
              js = d.createElement(s); js.id = id;
              js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
              fjs.parentNode.insertBefore(js, fjs);
            }(document, 'script', 'facebook-jssdk'));

            this.inited = true;
        },

        getAuth: function()
        {
            var senddata = { social : 'FB',  access_token : this.access_token };
            if (!WHP.auth.status)
            if (this.access_token!=null)
            {
                log("WHP.auth : get auth for FB...");
                 this.jqxhr = $.ajax({
                    url: WHP.netcalls.fbAuthCall+"?r="+Math.random(),
                    timeout : WHP.netTimeOut,
                    data : senddata,
                    success: bind(this.onData, this),
                    error: bind(this.onError, this)
                 });
            }
        },

        onData: function(response, status, xhr)
        {
            var resp = getObjectJson(response);
            if (resp!=null)
            if (resp.error)
            {
                if (resp.error.code == "API_AuthFailed")
                {
                    if (this.showErrMsg)
                        this.showErrMsg("This account isn't linked with WeHeartPics");
                }else
                {
                    if (this.showErrMsg)
                        this.showErrMsg("Something went wrong");

                }
            }else{
                WHP.pages.settings.onData(resp);
                WHP.auth.setUser(resp.user);
                WHP.auth.setSession({ token: resp.user.token, id: resp.user.id , uid: resp.user.id });
                WHP.controller.onChangeAuthState(true);
                WHP.auth.onStartWork(resp);
            }
            //setClass(WHP.menu.loginButton[0], "controls_login_button");
            WHP.controller.setTitle();
        },

        onFBData: function(response)
        {
            if (response.status == "connected")
            {
                log("Facebook : user was succesfully connected! :)");
                var token = response.authResponse.accessToken;
                if (this.access_token!=token)
                {
                    //setClass(WHP.menu.loginButton[0], "controls_logout_button_procces");
                    log("Facebook : token = ["+token+"]");
                    this.access_token = token;
                    this.getAuth();
                }else{
                    log("Facebook : user was not connected! :(");
                }
            }
            WHP.controller.setTitle();
        },

        onError: function(e)
        {
            log("WHP/auth/FB : error while logging in!");
            WHP.controller.showErrorPage();
            //setClass(WHP.menu.loginButton[0], "controls_login_button");
            WHP.controller.setTitle();
        },

        login : function (e)
        {
            this.access_token = "";
            FB.login(bind(this.onFBData, WHP.auth.FB), { scope:'publish_actions,publish_stream,user_photos,offline_access,email,user_birthday'});
        },

        loginOG : function (e, _func)
        {

            this.access_token = "";
            FB.login(_func, { scope:'publish_actions,publish_stream,user_photos,offline_access,email,user_birthday'});
        },

        fbShareEvents : function(e)
        {
            log("CreateEdge");
            if (WHP.shares.onFbLike(e))
                return false;

            if (WHP.controller.curPage.onFBlike)
            {
                WHP.controller.curPage.onFBlike(e);
            }
        }
    },



    TW : {
        inited : false,
        jqxhr : null,
        requesttoken : null,
        req_count : 0,
        req_max : 10,
        preStatus : null,
        activeToken : false,
        curWind : null,

        showErrMsg : null,



        init: function ()
        {
              var js, fjs = document.getElementsByTagName('script')[0];
              if (document.getElementById('twitter-jssdk')) {return;}
              js = document.createElement('script');
              js.id = 'twitter-jssdk';
              $(js).load(bind(this.twLoadedCall,this));
              js.src = "//platform.twitter.com/widgets.js";
              fjs.parentNode.insertBefore(js, fjs);

            this.inited = true;
        },

        twLoadedCall : function(e)
        {
            //WHP.pages.photo.share.setShareEvents();
        },


        getReqToken : function()
        {
            log("login tw2 >");
            //active?t
            this.activeToken = true;
            this.jqxhr = $.ajax({
                url: WHP.netcalls.twReqTokenCall+"?"+Math.random(),
                timeout : WHP.netTimeOut,
                success: bind(this.onDataToken, this),
                error: bind(this.onErrorToken, this)
            });
        },

        onDataToken: function(response, status, xhr)
        {
            log("data token");
            this.activeToken = false;
            var resp = getObjectJson(response);

            if (resp.error)
            {
                log("WHP/auth/TW : got error while getting twitter token = ["+resp.error.code+"]");
                this.req_count++;
                this.getReqTokenAct();
            }else{
                log("WHP/auth/TW : get twitter request token = ["+resp.oauth_token+"]");
                this.req_count = 0;

                if ( this.curWind )
                    this.curWind.location.href = "http://api.twitter.com/oauth/authorize?oauth_token="+resp.oauth_token;
            }
        },

        onErrorToken: function(response)
        {
            this.activeToken = false;
            var status = response['status'];

            if (status==0)
            {
                //offline
                log("WHP/auth/TW : OFFLINE mode!");
            }else{
                this.getReqTokenAct();
                this.req_count++;
                log("WHP/auth/TW : error while getting twitter request token! Status = ["+status+"] Tries = ["+this.req_count+"]");
            }
        },


        getAuth: function(_id, _token, _secret)
        {
            log("GET TW AUTH = ["+_id+" : "+_token+" : "+_secret+"]");
            log("WHP/auth/TW : get auth...");

            if (WHP.auth.status)
            {
                WHP.pages.settings.linker.TW.finalLinkTw(_id, _token, _secret);
                return false;
            }


            //setClass(WHP.menu.loginButton[0], "controls_logout_button_procces");

            this.jqxhr = $.ajax({
                url: WHP.netcalls.fbAuthCall,
                timeout : WHP.netTimeOut,
                data : { r : Math.random(), social : 'tw' , access_token : _token, access_token_secret : _secret},
                success: bind(this.onData, this),
                error: bind(this.onError, this)
            });

        },

        onData: function(response, status, xhr)
        {
            var resp = getObjectJson(response);
                if (resp.error)
                {
                    if (resp.error.code == "API_AuthFailed")
                    {
                        if (this.showErrMsg)
                            this.showErrMsg("This account isn't linked with WeHeartPics");
                    }else
                    {
                        if (this.showErrMsg)
                            this.showErrMsg("Something went wrong");

                    }


                }else{
                    WHP.pages.settings.onData(resp);
                    WHP.auth.setUser(resp.user);
                    WHP.auth.setSession({ token: resp.user.token, id: resp.user.id , uid: resp.user.id });
                    WHP.controller.onChangeAuthState(true);
                    WHP.auth.onStartWork(resp);
                }
            //setClass(WHP.menu.loginButton[0], "controls_login_button");
            WHP.controller.setTitle();
        },


        onError: function(e)
        {
            log("WHP/auth/TW : error while logging in!");
            this.preStatus = null;
            //setClass(WHP.menu.loginButton[0], "controls_login_button");
        },

        login : function (e)
        {
            log("login tw >");
            this.req_count = 0;
            this.curWind = openWindow2("Twitter auth", 640, 480);
            this.getReqToken();
        }
    },


    STD : {
        showErrMsg : null,

        login: function(_login, _pw)
        {
            this.jqxhr = $.ajax({
                url: WHP.netcalls.mailLoginCall,
                timeout : WHP.netTimeOut,
                data : { r : Math.random(), login : _login, passw : _pw},
                success: bind(this.onData, this),
                error: bind(this.onError, this)
            });
        },

        onData: function(response, _reg)
        {
            var resp = getObjectJson(response);
            if (resp!=null)
            if (resp.error)
            {
                if (resp.error.code == "API_BadParams")
                {
                    if (this.showErrMsg)
                        this.showErrMsg("Wrong e-mail and password combination");
                }else if (resp.error.code == "API_AuthFailed")
                {
                    if (this.showErrMsg)
                        this.showErrMsg("Wrong e-mail and password combination");

                }else if (resp.error.code = "API_PendingConfirmation")
                {
                    if (this.showErrMsg)
                        this.showErrMsg("We have sent you an email to confirm");
                }else
                {
                    if (this.showErrMsg)
                        this.showErrMsg("Something went wrong");

                }

            }else{
                WHP.pages.settings.onData(resp);
                WHP.auth.setUser(resp.user);
                WHP.auth.setSession({ token: resp.user.token, id: resp.user.id , uid: resp.user.id });
                WHP.controller.onChangeAuthState(true);
                WHP.auth.onStartWork(resp);
            }
            //setClass(WHP.menu.loginButton[0], "controls_login_button");
            WHP.controller.setTitle();
        },


        onError : function(e)
        {
            if (this.showErrMsg)
                this.showErrMsg("Something went wrong");
        }
    }
}


WHP.actions.comments = {
	
	//post comments
	postComment : function (_photoId, _reply, _commentBody, _callback, _errorcb)
	{

		var curUrl = WHP.netcalls.commentsCallAdd;
        replyer = {};

		if (_reply)
		{
			curUrl = WHP.netcalls.commentsCallReply;
            replyer = { comment : _reply};
            WHP.stats.trackComment(true);
		}else{
            WHP.stats.trackComment();
        }
        //WHP.stats.checkVisible();

        var errcb = _errorcb;
        if (!errcb)
            errcb = bind(this.onPostCommentError, this);

        WHP.opengraph.makeCommentAction(_photoId);
		$.ajax({
			  url: curUrl,
			  data : $.extend( WHP.auth.status, { 'text' : _commentBody }, replyer, {r : Math.random(), photo : _photoId}),
			  timeout : WHP.netTimeOut,
			  success: _callback,
			  error: errcb
		});
	},	
	onPostCommentError : function (e)
	{
		log("WHP/actions/comments : Error while postiong comment!");
	},
	
	//get comments
	getComments: function (_photoId, _callback, _errorCallBack)
	{
        var erCall = bind(this.onError, this);
        if (_errorCallBack)
            erCall = _errorCallBack;

		$.ajax({
			  url: WHP.netcalls.commentsCallGet,
              data : { photo : _photoId, r : Math.random(), limit : 1000, offset : 0 },
			  timeout : WHP.netTimeOut,
			  success: _callback,
			  error: erCall
		});
	},
	//error callback
	onError : function (e)
	{
		log("WHP/actions/comments : Error while getting comments!");
	}
}

WHP.actions.likes = {
	//http://weheartpics.com/api/photo/{photo_id}/vote/?like={like}
	
	likePhoto : function (_id, _vote, _label)
	{
		if (!WHP.auth.status)
		{
			//show auth window 2
			WHP.menu.showLoginMenu2();
			return false;
		}

		var curVote = parseInt(_vote);

		if (isNaN(curVote))
			return false;

		curVote = Math.max(0, curVote);
		curVote = Math.min(1, curVote);
			
		$.ajax({
			  url: WHP.netcalls.voteCall,
			  data : { like : _vote , r : Math.random(), photo : _id },
			  timeout : WHP.netTimeOut,
			  success: bind(this.onData, this),
			  error: bind(this.onError, this)
		});

        if (curVote>0)
        {
            WHP.stats.trackLike(_label);
            WHP.opengraph.makeLikeAction(_id);
        }

	},
	
	onData : function (response, status, xhr)
	{
		var resp = getObjectJson(response);	
		if (resp.error)
		{
			log("WHP/actions/likes : Err = ["+resp.error.code+"]");
			//WHP.controller.showErrorPage();
			WHP.errors.hasNetError(resp);
			return false;
		}
        WHP.stats.trackLike();
        //WHP.stats.checkVisible();
		
	},
	onError : function (e)
	{
		log("WHP/actions/likes : Error while loading actual data! Err = ["+e+"]");
	},
	
	
	
	getLikeList : function (_id, callBack)
	{
		$.ajax({
			  url: WHP.netcalls.likesCall,
			  data : $.extend(WHP.auth.status, {r : Math.random(), photo : _id}),
			  timeout : WHP.netTimeOut,
			  success: callBack,
			  error: bind(this.onError2, this)
		});
	},

	onError2 : function (e)
	{
		log("WHP/actions/likes : Error while loading actual data! Err = ["+e+"]");
	}
}



WHP.menu = {
	inited : false,
	panelAuth : null,
	panelMenu : null,
	menuObject : null,
	menuA : null,
	menuNA : null,
	notifyNelem : null,
	
	loginButton : null,
	logoutButton : null,
		

	
	menuShadow : null,
	
	randomButton : null,
	
	storiesRollover : false,
	animateMenuShadow : true,

    downloadButtons : null,
	
	stories_wind : null,
	
	windowsScrollsDown : [],


    main_link_logo :  null,
			
	//init function
	init: function ()
	{	
		log('menu_init');
		$('html').click(bind(this.htmlClick, this));
		$('html').mouseup(bind(this.htmlMouseUp, this));
		$('html').mousemove(bind(this.htmlMouseMove, this));
		
		this.panelAuth = document.getElementById("header_controls");
		this.panelMenu = document.getElementById("main_content");
		this.menuObject = $("#menu_layer");
		
		this.randomButton = $(this.panelAuth).find( ".randombutton" ).get()[0];
		AddHandler(this.randomButton, 'click', bind(WHP.randomPage.clickButton, WHP.randomPage));
        if (browser.ipad)
        {
		    setButton1s1i(this.randomButton, "randombutton", 300);
        }else{
            setButton1s1i(this.randomButton, "randombuttonweb", 300);
            setClass(this.randomButton, "randombuttonweb");
        }
		
		this.menuShadow = $(this.panelMenu).find( ".menu_shadow_menu" );
        this.menuShadow.css("pointer-events", "none");
		this.setShadowA(0);
		
		this.menuA = $(this.panelAuth).find( ".auth_controls" );
        this.menuA.links = $(this.menuA).find( ".controls_link_text" );



		this.menuNA = $(this.panelAuth).find( ".noauth_controls" );
		this.notifyNelem = $(this.panelAuth).find( ".controls_notify_text_null" );
		
		//menu button events
		this.loginButton = this.menuNA.find(".controls_login_container").find(".controls_link_text_red");
		this.logoutButton = $(this.panelAuth).find( ".controls_logout_button" );
		this.logoutButton.click( function(e){ WHP.auth.logout();e.stopPropagation(); } );
		this.loginButton.click( function(e){ WHP.loginMenus.showLoginMenu();e.stopPropagation(); } );
		
		//auth

		//this.loginOthersWind = $(this.panelAuth).find( ".noauth_controls" );

		AddHandler(window, "scroll", bind(this.onScrollEvent, this), this);
		
		
		addIntelloLinks( $('#menu_layer') );

        this.main_link_logo = $('#menu_layer').find(".main_link_logo");
        this.main_link_logo.click(bind(this.logoClickFunc, this));

        //downloadlinks
        this.downloadButtons  = $(this.panelMenu).find(".controls_download_button");
        this.downloadButtons.click(function(e){
            WHP.stats.trackDownloadButtonMenu(WHP.download.showNew);
            WHP.download.clickButton(this);
            cancelEvent(e);});

        WHP.loginMenus.init();

		
		this.inited = true;
	},

    logoClickFunc: function (e)
    {
        if  (WHP.auth.status)
        {
            WHP.controller.navigateTo(WHP.pages.timeline.urlStr);
        }else{
            WHP.controller.navigateTo(WHP.pages.landing.urlStr);
        }

        return cancelEvent(e);
    },
	
	downListEvent: function (elem)
	{
		this.windowsScrollsDown.push(elem);
	},
	
	htmlMouseMove: function (e)
	{
		var newX = e.pageX;
		var newY = e.pageY;
		var e = {x:newX, y:newY};
		for (var i=0; i<this.windowsScrollsDown.length; i++)
		{
            if (this.windowsScrollsDown[i].mouseMoveEvent)
			    this.windowsScrollsDown[i].mouseMoveEvent(e);
		}
	},
	
	htmlMouseUp: function (e)
	{
		while (this.windowsScrollsDown.length>0)
		{
			var a = this.windowsScrollsDown.pop();
			a.mouseup(e);
			//a.trigger(evt);
		}
	},
	
	htmlClick: function (e)
	{
        log("HTML CLIK");
        if (!WHP.controller.inited)
            return false;


        //menus
		WHP.loginMenus.hideLoginMenu();
		WHP.loginMenus.hideLoginMenu2();
        WHP.pages.settings.hideWindow1();
        WHP.popup_message.hideAlert();

        WHP.pages.settings.hideWindow2();
        WHP.pages.settings.hideWindow1();

        WHP.pages.profile.hideWindow1();
			
		if (WHP.notifications.wind.visible)
			WHP.notifications.hide();

        if (WHP.download.wind.visible)
            WHP.download.hide();
			
		if ( WHP.pages.user.pointsHelper.windCont.style.display == "block" )
			WHP.pages.user.pointsHelper.hide();
			
		if ( WHP.pages.profile.pointsHelper.windCont.style.display == "block" )
			WHP.pages.profile.pointsHelper.hide();
	},
	
	onScrollEvent: function (e)
	{
        var scrollTop = getScrollTop();
		
		if (this.animateMenuShadow)
			this.setShadow(scrollTop);
	},
	
	setShadowA: function (_C)
	{
		var C = _C;	
		C = Math.max(C, 0);
		C = Math.min(C,1);
		this.menuShadow.alpha = C;
		setAlpha(this.menuShadow, C);


        if (browser.ie)
        {
          // alert("Has layout = ["+ this.menuShadow.get()[0].hasLayout+"]");
        }
	},
	
	setShadow: function (scrollTop)
	{
		var topSpace1 = 2;
		var animSpace = 40;
			
		var C = 0;
		if (scrollTop<topSpace1)
		{
			C = 0;
		}else if (scrollTop<topSpace1+animSpace)
		{
			C = (scrollTop-topSpace1)/animSpace;
		}else{
			C = 1;
		}
		
		this.setShadowA(C);
	},
	
	setNotifyNumber: function (_n)
	{
        log("Set notify = ["+_n+"]");
		var N = parseInt(_n);
		if (isNaN(N))
			N = 0;
		N = Math.max(N,0);

        log("Set notify = ["+N+"]");
		this.notifyNelem.text(N+"");
		if (N==0)
		{
			setClass(this.notifyNelem,"controls_notify_text_null");
		}else{
			setClass(this.notifyNelem,"controls_notify_text_active");
		}
			
	},
	




	setLinkState : function(_ar)
	{
		var locationS = new String(document.location);
        locationS = locationS.toLowerCase();

		for (var i=0; i<_ar.length; i++)
		{
			var me = _ar[i];
            var meHref = new String(me.href);
            meHref = meHref.replace("http://"+WHP.domain,"");
            meHref = meHref.replace("https://"+WHP.domain,"");
            meHref = meHref.replace("http://weheartpics.com","");
            meHref = meHref.replace("//"+WHP.domain+"/","");

            //remove ?query
            if (meHref.indexOf("?")>-1)
                meHref = meHref.substring(0, meHref.indexOf("?"));

            meHref = normolizeLink(meHref);
            meHref = ".com/"+meHref;

            if (browser.ie)
            {

                if (locationS.indexOf("#")>-1)
                {
                    var str = locationS.substring(locationS.indexOf("#"), locationS.length);

                    if ( this.linkChecker(str,meHref) )
                    {
                        setClass(me, "controls_link_text_active");
                    }else{
                        setClass(me, "controls_link_text");
                    }
                }else{
                    if ( this.linkChecker(locationS,meHref) )
                    {
                        setClass(me, "controls_link_text_active");
                    }else{
                        setClass(me, "controls_link_text");
                    }
                }
            }else{
                if ( this.linkChecker(locationS,meHref) )
                {
                    setClass(me, "controls_link_text_active");
                }else{
                    setClass(me, "controls_link_text");
                }
            }

		}		
	},

    checkMenuState: function ()
    {
        if (WHP.auth.status)
        {
            this.menuA.css({ display : 'block' });
            setClass(this.logoutButton[0], "controls_logout_button");
            this.menuNA.css({ display : 'none' });
        }else{
            this.menuA.css({ display : 'none' });
            //setClass(WHP.menu.loginButton[0], "controls_login_button");
            this.menuNA.css({ display : 'block' });
        }
    },

    transformLinks : function()
    {
        var profileLink = WHP.menu.menuA.links[0];

        //profile on auth
        if (WHP.auth.status)
        {
            //set profile
            log("CHANGE = ["+$(WHP.menu.menuA.links[1]).attr("href")+"]");

            $(WHP.menu.menuA.links[1]).attr("href", WHP.links.getUserProfileLink(WHP.auth.status.id));
        }
    },

    linkChecker : function (_loc, _link)
    {
        var blood = false;

        if (_loc.indexOf(_link)>=0)
        {
            blood = true;
        }
        return blood;
    },
	
	currentMenuPos : function()
	{
        this.transformLinks();
		if (WHP.auth.status)
		{
			var elem = this.menuA;
		}else{
			var elem = this.menuNA;
		}
		var active = elem.find( ".controls_link_text_active" );
		var deactive = elem.find( ".controls_link_text" );
		var location = new String(document.location);
		this.setLinkState(active);
		this.setLinkState(deactive);
    }
}




WHP.loginMenus = {
    loginWindowWind : null,
    loginWindowWind2 : null,

    init : function()
    {
        this.loginWindowWind = $(WHP.menu.menuNA).find( ".controls_auth_window" );
        this.loginWindowWind.click(bind(function(event) {
            event.stopPropagation();
        }, this));
        this.setLoginWindow(this.loginWindowWind);
        this.loginWindowWind.hide = bind(this.hideLoginMenu, this);


        this.loginWindowWind2 = $("#controls_auth_window2" );
        this.loginWindowWind2.css({ position : 'fixed' });
        this.loginWindowWind2.click(bind(function(event) {
            event.stopPropagation();
        }, this));
        this.setLoginWindow(this.loginWindowWind2);
        this.loginWindowWind2.hide = bind(this.hideLoginMenu2, this);


    },



    showLoginMenu : function()
    {

        this.loginWindowWind.css({ display : 'block' });


        this.loginWindowWind.reset();
        this.hideLoginMenu2();
    },

    showLoginMenu2 : function()
    {
        this.loginWindowWind2.css({ display : 'block' });
        this.loginWindowWind2.reset();

        var scrollTop = getScrollTop();

        var dt = 0;
        if (WHP.controller.curPage.urlStr == "photo")
            dt = -10;

        var H = 300;
        if ($(this.loginWindowWind2).css('display') == 'block')
        {
            if (browser.ie)
            {

                this.loginWindowWind2.css({ position : 'absolute' });
                this.loginWindowWind2.css({ top : (scrollTop + (WHP.screenH - H)*0.5 )+'px', left : (WHP.screenWl-285)*0.5+dt +'px' });
            }else
                this.loginWindowWind2.css({ top : (WHP.screenH - H)*0.5 +'px', left : (WHP.screenWl-285)*0.5+dt +'px' });
            //cancelEvent(e);
        }




        this.hideLoginMenu();

        WHP.main_fader.show();
    },

    hideLoginMenu : function()
    {
        log("HIDE LOGIN 1");
        if (this.loginWindowWind.css("display") == 'none')
            return false;

        this.loginWindowWind.css({ display : 'none' });
    },

    hideLoginMenu2 : function()
    {
        log("HIDE LOGIN 2");
        if (this.loginWindowWind2.css("display") == 'none')
            return false;

        this.loginWindowWind2.css({ display : 'none' });
        WHP.main_fader.hide();
    },

    setLoginWindow : function(_wind)
    {
        _wind.parent = this;
        _wind.states = _wind.find(".login_box");

        for (var i=0; i<_wind.states.length; i++)
        {
            _wind.states[i] = $(_wind.states[i]);
            _wind.states[i].a0 = 0;
            _wind.states[i].a1 = 0;
            _wind.states[i].aC = 0;
            _wind.states[i].p0 = 0;
            _wind.states[i].p1 = 0;
            _wind.states[i].pC = 0;
            _wind.states[i].dir = 0;
            _wind.pos = { x1 : 0, x2 : 0 };
            _wind.states[i].visible = false;
            _wind.states[i].parent = _wind;

            _wind.states[i].setVisible = bind( function(_a){
                if (_a)
                {
                    this.aC = 1;
                    this.pC = 1.0;
                    this.css({ display : ''});
                    this.visible = true;
                }else{
                    this.aC = 0;
                    this.pC = 0;
                    this.css({ display : 'none'});
                    this.visible = false;
                }
                this.setPos();

                this.dir = 0;
                this.timer.reset();
            }, _wind.states[i]);

            _wind.states[i].hide = bind( function(){
                if (this.dir==-1)
                    return false;
                this.a0 = this.aC;
                this.a1 = 0.0;
                this.p0 = this.pC;
                this.p1 = 0.0;
                this.dir = -1;
                this.setPos();

                this.timer.reset();
                this.timer.start();
            }, _wind.states[i]);
            _wind.states[i].N = new Number(i);
            _wind.states[i].show = bind( function(){
                if (this.dir==1)
                    return false;
                this.a0 = this.aC;
                this.a1 = 1.0;
                this.p0 = this.pC;
                this.p1 = 1.0;
                this.dir = 1;
                this.visible = true;
                this.css({ display : ''});
                this.setPos();

                this.timer.reset();
                this.timer.start();
            }, _wind.states[i]);
            _wind.states[i].setPos = bind( function(){
                setAlpha(this, this.aC);
                this.css({ height: this.H*this.pC +"px"});
            },_wind.states[i]);
            _wind.states[i].timer = new Timer(1000/30, 15);
            _wind.states[i].timer.onTimerEvent = bind(function(e){
                var A = e.currentCount/e.repeatCount;
                var d = 0.5;
                var A1 = Math.max(0, Math.min(1, A/d));
                A1 = (Math.sin(Math.PI*(A1-0.5))+1)*0.5;
                var A2 = Math.max(0, Math.min(1, (A-d)/(1-d)));
                A2 = (Math.sin(Math.PI*(A2-0.5))+1)*0.5;

                if (this.dir>0)
                {
                    //+
                    this.aC = (1-A2)*this.a0 + A2*this.a1;
                    this.pC = (1-A1)*this.p0 + A1*this.p1;
                    this.setPos();
                }else{
                    //-
                    this.aC = (1-A1)*this.a0 + A1*this.a1;
                    this.pC = (1-A2)*this.p0 + A2*this.p1;
                    this.setPos();
                }

                if (A==1)
                {
                    if (this.dir>0)
                    {
                        //+

                        if (this.N == 1)
                        {
                            if (validateEmail(this.parent.login_mailInput.val()))
                            {
                                this.parent.login_passInput.focus();
                            }else{
                                this.parent.login_mailInput.focus();
                            }

                        }
                    }else{
                        //-
                        this.css({ display : 'none'});
                        this.visible = false;

                        if (this.N == 0)
                        {
                           this.parent.states[3].show();
                        }


                    }
                    this.dir = 0;


                }
            },_wind.states[i]);
            _wind.states[i].H = 0;
        }

        _wind.states[0].H = 120; //sigh in logos
        _wind.states[1].H = 154; //enter login pass
        _wind.states[2].H = 65; //register with mail
        _wind.states[3].H = 154; //register with mail enter
        _wind.states[4].H = 154; //register with mail enter
        _wind.states[5].H = 154; //confirmation
        _wind.states[6].H = 250; //connect


        _wind.buttonFB = _wind.states[0].find(".signin_fb_button");

        _wind.buttonTW = _wind.states[0].find(".signin_tw_button");

        _wind.buttonMAIL = _wind.states[0].find(".signin_mail_button");
        _wind.buttonMAIL.click(bind(function(){
            this.setState(1);
        },_wind));

        _wind.buttonReg = _wind.states[2];
        _wind.buttonReg.click(bind(function(){
            if ((this.state==0) || (this.state==1))
            this.setState(2);
        },_wind));

        _wind.forgetButton =  _wind.states[1].find(".form_forgot");
        _wind.forgetButton.click(bind(function(){
            WHP.controller.navigateTo(WHP.pages.resendpw.urlStr);
        },_wind));


        //
        var oks = _wind.states[6].find(".ok_mini");

        _wind.ok1 = $(oks[0]);
        _wind.ok2 = $(oks[1]);
        _wind.fbLinksButton = _wind.states[6].find(".signin_fb_button");
        _wind.fbLinksButton.click(bind(function() {
            if (this.linkedFb)
                return false;
            WHP.pages.settings.linker.FB.showErrMsg = this.showErrMsg4;
            WHP.pages.settings.linker.FB.onLink = bind(this.linkFbCallback,this);
            WHP.pages.settings.linker.FB.linkFb();
        }, _wind));

        _wind.twLinksButton = _wind.states[6].find(".signin_tw_button");
        _wind.twLinksButton.click(bind(function() {
            if (this.linkedTw)
                return false;
            WHP.pages.settings.linker.TW.showErrMsg = this.showErrMsg4;
            WHP.pages.settings.linker.TW.onLink = bind(this.linkTwCallback,this);
            WHP.pages.settings.linker.TW.linkTw();
        }, _wind));
        _wind.linkTwCallback = bind(function(response){
            this.linkedTw = true;
            this.ok1.css( { visibility : "visible"});
        }, _wind);
        _wind.linkFbCallback = bind(function(response){
            this.linkedFb = true;
            this.ok2.css( { visibility : "visible"});
        }, _wind);


        _wind.errorMessageTimeout4  = -1;
        _wind.hideMsg4 = bind(function()
        {
            if (this.errorMessageTimeout4!=-1)
                clearTimeout(this.errorMessageTimeout4);
            this.errorMessageTimeout4 = setTimeout(bind(function() { _wind.error4.text(""); this.errorMessageTimeout4 = -1; }, this),WHP.errorMessTO);
        },_wind);

        _wind.showErrMsg4 = bind(function(_txt)
        {
            _wind.error4.text(_txt);
            this.hideMsg4();
        },_wind);
        _wind.error4 = _wind.states[6].find(".form_error_message");
        _wind.linkedTw = false;
        _wind.linkedFb = false;



        //
        var inputs = _wind.states[3].find(".form_input_field_sign");
        _wind.mailInput =  $(inputs[0]);
        _wind.passInput =  $(inputs[1]);
        _wind.mail = "";
        _wind.pass = "";
        _wind.submit1 = _wind.states[3].find(".form_confirm_button");
        _wind.error1 = _wind.states[3].find(".form_error_message");
        _wind.reset1 = bind(function(){
            this.mailInput.val(this.mail);
            this.passInput.val(this.pass);
        }, _wind);

        var inputs = _wind.states[4].find(".form_input_field_sign");
        _wind.firstName =  $(inputs[0]);
        _wind.lastName =  $(inputs[1]);
        var buttons = _wind.states[4].find(".form_confirm_button2");
        _wind.submit2Back = $(buttons[0]);
        _wind.submit2 = $(buttons[1]);
        _wind.error2 = _wind.states[4].find(".form_error_message");
        _wind.reset2 = bind(function(){
            this.firstName.val(this.fn);
            this.lastName.val(this.ln);
        }, _wind);

        //

        _wind.errorMessageTimeout3 = -1;
        _wind.hideMsg3 = bind(function()
        {
            if (this.errorMessageTimeout3!=-1)
                clearTimeout(this.errorMessageTimeout3);
            this.errorMessageTimeout3 = setTimeout(bind(function() { _wind.error3.text(""); this.errorMessageTimeout3 = -1; }, this),WHP.errorMessTO);
        },_wind);

        _wind.showErrMsg3 = bind(function(_txt)
        {
            _wind.error3.text(_txt);
            this.hideMsg3();
        },_wind);
        _wind.submitConfirmation = _wind.states[5].find(".form_confirm_button");
        _wind.error3 = _wind.states[5].find(".form_error_message");


        _wind.resendOk = bind(function(response)
        {
            var resp = getObjectJson(response);
            if (resp.error)
            {
                log("WHP/registration : error while loading page data! Err =["+response+"]");
                if (resp.error.code == "API_Rejected")
                {
                    this.showErrMsg3("Email already sent. Please check your mail");
                }else if (resp.error.code == "API_ObjectNotFound")
                {
                    this.showErrMsg3("User wasn't found");
                }else if (resp.error.code == "API_BadParams")
                {
                    this.showErrMsg3("User wasn't found");
                }
                return false;
            }

        }, _wind);

        _wind.resendFail = bind(function(e)
        {
            this.showErrMsg3("Something went wrong");
        }, _wind);

        _wind.resendConfirmation = bind(function(){
            $.ajax({
                url:WHP.netcalls.resendCall,
                data : { r : Math.random(), login :  this.mail },
                timeout:WHP.netTimeOut,
                method : "POST",
                success:bind(this.resendOk, this),
                error:bind(this.resendFail, this)
            });
        }, _wind);

        _wind.submitConfirmation.click(bind(_wind.resendConfirmation, _wind));



        //scenario 1

        _wind.mailInput.keypress(bind(function(e)
        {
            if (e.keyCode == 13){this.applyForm1();}
        },_wind));
        _wind.passInput.keypress(bind(function(e)
        {
            log("PASS");
            var password = this.passInput.val();
            if  (password.length>=16)
            {
                this.showErrMsg1("You can't use more than 16 characters");
            }

            if (e.keyCode == 13){this.applyForm1();}
        },_wind));

        _wind.applyForm1 = bind(function(){
            log("1");
            var email =  this.mailInput.val();
            var password = this.passInput.val();

            if (!validateEmail(email))
            {
                this.showErrMsg1("Doesn't look like a valid email");
                this.mailInput.focus();
                return false;
            }


            if (password.length<6)
            {
                this.showErrMsg1("Please use at least 6 characters");
                this.passInput.focus();
                return false;
            }


            //WHP.auth.STD.showErrMsg = this.showErrMsg1;
            //WHP.auth.STD.login(email, password);
            this.mail = email;
            this.pass = password;

            this.setState(3);

        }, _wind);
        _wind.submit1.click(bind(_wind.applyForm1, _wind));

        _wind.errorMessageTimeout1 = -1;
        _wind.hideMsg1 = bind(function()
        {
            if (this.errorMessageTimeout1!=-1)
                clearTimeout(this.errorMessageTimeout1);
            this.errorMessageTimeout1 = setTimeout(bind(function() { _wind.error1.text(""); this.errorMessageTimeout1 = -1; }, this),WHP.errorMessTO);
        },_wind);

        _wind.showErrMsg1 = bind(function(_txt)
        {
            _wind.error1.text(_txt);
            this.hideMsg1();
        },_wind);




        //s2

        _wind.firstName.keypress(bind(function(e)
        {
            var password = this.firstName.val();
            if  (password.length>=32)
            {
                this.showErrMsg2("You can't use more than 32 characters");
            }


            if (e.keyCode == 13){this.applyForm2();}
        },_wind));
        _wind.lastName.keypress(bind(function(e)
        {
            var password = this.lastName.val();
            if  (password.length>=32)
            {
                this.showErrMsg2("You can't use more than 32 characters");
            }


            if (e.keyCode == 13){this.applyForm2();}
        },_wind));

        _wind.errorMessageTimeout2 = -1;
        _wind.hideMsg2 = bind(function()
        {
            if (this.errorMessageTimeout2!=-1)
                clearTimeout(this.errorMessageTimeout2);
            this.errorMessageTimeout2 = setTimeout(bind(function() { _wind.error2.text(""); this.errorMessageTimeout2 = -1; }, this),WHP.errorMessTO);
        },_wind);

        _wind.showErrMsg2 = bind(function(_txt)
        {
            _wind.error2.text(_txt);
            this.hideMsg2();
        },_wind);

        _wind.netConnect2 = false;
        _wind.applyForm2 = bind(function(){
            if (this.netConnect2)
                return false;

            var fn =  this.firstName.val();
            var ln = this.lastName.val();

            if (fn.length==0)
            {
                this.showErrMsg2("Enter your first and last name");
                this.firstName.focus();
                return false;
            }

            if (ln.length==0)
            {
                this.showErrMsg2("Enter your first and last name");
                this.lastName.focus();
                return false;
            }


            this.fn = fn;
            this.ln = ln;
            this.netConnect2 = true;
            $.ajax({
                url:WHP.netcalls.regCall,
                data : { r : Math.random(), login :  this.mail, passw : this.pass, first_name : fn, last_name : ln },
                timeout:WHP.netTimeOut,
                method : "POST",
                success:bind(this.onRegOk, this),
                error:bind(this.onRegFail, this)
            });

        }, _wind);
        _wind.submit2.click(bind(_wind.applyForm2, _wind));
        _wind.submit2Back.click(bind(function(){

            this.fn =  this.firstName.val();
            this.ln = this.lastName.val();

            this.hideStates();
            this.states[2].setVisible(true);
            this.states[3].setVisible(true);

            this.reset2();

        }, _wind));



        _wind.onRegOk = bind(function(response){
            this.netConnect2 = false;
            var resp = getObjectJson(response);
            if (resp.error)
            {
                if (resp.error.code == "API_AlreadyInUse")
                {
                    this.showErrMsg1("This email already registered");
                    this.setState(6);
                    return false;
                }
                this.showErrMsg2("Something went wrong");
                return false;
            }


            //check pending
            if (resp.state == "PENDING_CONFIRMATION")
            {
                this.setState(4);
                return false;
            }

            WHP.auth.STD.onData(resp, true);
            //this.setState(5);
            WHP.controller.navigateTo(WHP.pages.findfriends.urlStr);


        }, _wind);

        _wind.onRegFail = bind(function(response){
            this.netConnect2 = false;
            this.showErrMsg2("Something went wrong");
        }, _wind);




        _wind.setState = bind(function(_newState){
            this.state = _newState;

            if (this.state == 1)
            {
                this.states[1].show();
                return false;
            }

            if (this.state == 2)
            {
                this.states[1].hide();
                this.states[0].hide();
                //this.states[3].show(true);
                this.buttonReg.css({ cursor : "auto" });
                this.reset1();
                return false;
            }

            if (this.state == 3)
            {
                this.hideStates();
                this.states[2].setVisible(true);
                this.states[4].setVisible(true);
                this.firstName.focus();
                this.reset2();
                this.buttonReg.css({ cursor : "auto" });
                return false;
            }

            if (this.state == 4)
            {
                this.hideStates();
                this.states[5].setVisible(true);
                return false;
            }

            if (this.state == 5)
            {
                this.hideStates();
                this.states[6].setVisible(true);
                return false;
            }

            if (this.state == 6)
            {
                this.hideStates();
                this.states[2].setVisible(true);
                this.states[3].setVisible(true);
                this.mailInput.focus();
                this.reset1();
                return false;
            }

        },_wind);


        _wind.hideStates = bind( function() {
            for (var i=0; i<this.states.length; i++)
            {
                this.states[i].setVisible(false);
            }
        },_wind);

        _wind.state = 0;
        _wind.newState = 0;
        _wind.reset = bind(function() {
            this.fn = "";
            this.ln = "";
            this.mail = "";
            this.pass = "";

            this.hideStates();
            this.states[0].setVisible(true);
            this.states[2].setVisible(true);
            this.state = 0;

            this.ok1.css( { visibility: "hidden"});
            this.ok2.css( { visibility: "hidden"});
            this.login_passInput.val("");

            this.buttonReg.css({ cursor : "pointer" });

            this.linkedTw = false;
            this.linkedFb = false;

        },_wind);

        _wind.timer = new Timer(1000/30, 12);
        _wind.timer.onTimerEvent = bind( function(e){
            var A = e.currentCount/e.repeatCount;
            var d = 0.5;
            var A1 = Math.min(1, Math.max(0, A/d));
            var A2 = Math.min(1, Math.max(0, (A-d)/(1-d)));



            if (A == 1)
            {
                this.state = this.newState;
            }

        },_wind);


        _wind.errorMessageTimeout4 = -1;
        _wind.hideMsg4 = bind(function()
        {
            if (this.errorMessageTimeout4!=-1)
                clearTimeout(this.errorMessageTimeout4);
            this.errorMessageTimeout4 = setTimeout(bind(function() { _wind.error4.text(""); this.errorMessageTimeout4 = -1; }, this),WHP.errorMessTO);
        },_wind);

        _wind.showErrMsg4 = bind(function(_txt)
        {
            _wind.error4.text(_txt);
            this.hideMsg4();
        },_wind);

        _wind.error4 = _wind.states[1].find(".form_error_message");
        _wind.loginButton = _wind.states[1].find(".form_confirm_button");
        var inputs =  _wind.states[1].find(".form_input_field_sign");
        _wind.login_mailInput = $(inputs[0]);
        _wind.login_passInput = $(inputs[1]);
        _wind.submitLogin = bind(function(){
            var email =  this.login_mailInput.val();
            var password = this.login_passInput.val();

            if (!validateEmail(email))
            {
                this.showErrMsg4("Doesn't look like a valid email");
                this.login_mailInput.focus();
                return false;
            }



            WHP.auth.STD.showErrMsg = this.showErrMsg4;
            WHP.auth.STD.login(email, password);

        },_wind);
        _wind.loginButton.click(bind(_wind.submitLogin,_wind));
        _wind.login_mailInput.keypress(bind(function(e)
        {
            if (e.keyCode == 13){this.submitLogin();}
        },_wind));
        _wind.login_passInput.keypress(bind(function(e)
        {
            if (e.keyCode == 13){this.submitLogin();}
        },_wind));



    },

    hideMenus : function()
    {
        this.hideLoginMenu2();
        this.hideLoginMenu();
    }

}


WHP.pages.landing = {
    urlStr : "",	//temp name for error page
    title : "",
    rndEnable : false,
    inited : false,
    mainObject : null,

    sendMailObj : null,

    activeSend : false,


    init: function ()
    {
        this.mainObject = id$('landing_page');
        this.sendMailObj = $(this.mainObject).find(".landin_android");

        var dn = $(this.mainObject).find(".timeline_empty_download_iphone");
        dn.click(function() { WHP.stats.trackDownload("DOWNLOAD_LANDING") });


        if (browser.opera)
        {
            var a = $(this.mainObject).find(".landin_spacer");
            a.css( {height : 773+'px'});

            var b = $(this.mainObject).find(".landin_share_cont");
            b.css({ bottom : -33+'px'});
        }

        this.setUpemptyElement();

        this.inited = true;
    },

    setMissed : function(elem, missed)
    {
        elem.click(bind(function(){ this.missed.css({ display: 'block' }); this.timer.reset(); this.timer.start(); }, elem));
        elem.timer = new Timer(1500,1);
        elem.timer.onTimerEvent = bind(function(e){ log("END TIMER"); this.missed.css({ display: 'none'}) }, elem);
        elem.missed = missed;
    },



    onResizeEvent : function(e)
    {

    },


    show: function (_q)
    {
        //_q - query string
        WHP.controller.showCanvas();
        WHP.controller.setTitle();
        WHP.stats.trackShowMainButton();
    },

    hide: function ()
    {

    },

    setUpemptyElement : function()
    {
        this.sendMailObj.defText = "Your e-mail address...";
        this.sendMailObj.input = this.sendMailObj.find(".timeline_empty_enter");
        this.sendMailObj.input.val(this.sendMailObj.defText);
        this.sendMailObj.inputs = this.sendMailObj.find(".timeline_empty_inputs");
        this.sendMailObj.outputs = this.sendMailObj.find(".timeline_empty_inputs");
        this.sendMailObj.parent = this;


        this.sendMailObj.formButton = this.sendMailObj.find(".timeline_empty_notify_0");
        if (this.sendMailObj.formButton.length == 0)
            this.sendMailObj.formButton = this.sendMailObj.find(".timeline_empty_notify_1");

        this.sendMailObj.activeSend = false;

        this.sendMailObj.input.focus(bind(this.onFocus, this.sendMailObj));
        this.sendMailObj.input.blur(bind(this.onBlur, this.sendMailObj));
        this.sendMailObj.input.keyup(bind(this.checkInput, this.sendMailObj));

        this.sendMailObj.formButton.click(bind(this.sendRequest, this.sendMailObj));

        setClass(this.sendMailObj.formButton, "timeline_empty_notify_0");
        if (browser.opera)
        {
           this.sendMailObj.formButton.css({ position : 'relative', top : 3+'px'});
        }else if (browser.ie)
        {
           this.sendMailObj.formButton.css({ position : 'relative', top : 1+'px'});
        }


    },

    checkInput : function(e)
    {
        if (validateEmail(this.input.val()))
        {
            setClass(this.formButton, "timeline_empty_notify_1");
        }else{
            setClass(this.formButton, "timeline_empty_notify_0");
        }
    },


    onFocus : function(e)
    {
        if (this.input.val() == this.defText)
            this.input.val("");
    },

    onBlur : function(e)
    {
        if (this.input.val() == "")
            this.input.val(this.defText);
    },

    sendRequest : function(e)
    {
        if (this.activeSend)
            return false;

        if (!validateEmail(this.input.val()))
            return false;

        //http://weheartpics.com/api/promo/?email=rtbwerbrt%40wrerver.rr


        $.ajax({
            url:WHP.netcalls.promoCall,
            data : { r : Math.random(), email :  this.input.val() },
            timeout:WHP.netTimeOut,
            success:bind(this.parent.promoOk, this),
            error:bind(this.parent.promoFail, this)
        });
    },

    promoOk : function(e)
    {
        this.inputs.css({display : 'none'});
        setClass(this.outputs, "timeline_empty_output");
        this.outputs.css({display : 'block' }).html("We will email you when<br/>it is ready. See you soon!");
        this.activeSend = false;
    },

    promoFail : function (e)
    {
        this.inputs.css({display : 'block'});
        setClass(this.outputs, "timeline_empty_output_fail");
        this.outputs.css({display : 'block' }).html("Failed! <br/>Please, try again!");
        this.activeSend = false;
    },

    onAuthChange : function (_auth)
    {
        if (_auth)
        {
            WHP.controller.navigateTo(WHP.pages.timeline.urlStr);
        }
    },


    restore: function ()
    {
        WHP.controller.showCanvas();
    }
}



WHP.pages.error404 = {
	urlStr : "404",	//temp name for error page
	title : "",
	rndEnable : true,
	inited : false,
	mainObject : null,

    errorCont : null,
    errorHolder : null,


    fm : null,
		
	init: function ()
	{
		this.mainObject = id$('404');
		this.inited = true;

        this.errorCont = $(this.mainObject).find(".error_container");
        this.errorHolder = $(this.mainObject).find(".error_holder");

        this.fm = $(this.mainObject).find(".failman1");
    },

    onResizeEvent : function(e)
    {
        var w1 = this.errorHolder.width();
        var h1 = this.errorHolder.height();

        var w2 = 996;
        var h2 = Math.max(0,WHP.screenHl-120);

        this.errorHolder.css({ left : 0.5*(w2-w1)+'px', top : Math.max(0, 0.5*(h2-h1))+'px'});
    },

    setView : function(_message)
    {
		//alert(_message);
        if (_message == 1)
        {
            this.fm.attr("src", "./resouce/images/public/failman.png");
        }else if (_message == 2){
            this.fm.attr("src", "./resouce/images/public/failman2.png");
        }else if (_message == 3){
            this.fm.attr("src", "./resouce/images/public/failman_4.png");
        }else if (_message == 4){
            this.fm.attr("src", "./resouce/images/public/failman_5.png");
        }

        else{
            this.fm.attr("src", "./resouce/images/public/failman.png");
        }
    },

	show: function (_q)
	{
		//_q - query string
		WHP.controller.showCanvas();
		WHP.controller.setTitle();
        this.onResizeEvent();

	}
}




WHP.pages.photoPopular = {
	//controller parametres
	urlStr : "popular",
	title : "Popular",
	rndEnable : true,
	inited : false,
	
	mainObject : null,	
	feedObject : null,
	
			
	//init function
	init: function ()
	{
		this.mainObject = id$('popular');
		this.feedObject = new whp_feed_proto();
		
		
		var feed_cont = $(this.mainObject).find(".popular_photo_box");
		this.feedObject.init(feed_cont);	
		
		this.feedObject.urlPrefix = this.urlStr;
		this.feedObject.changeUrl = true;
        this.feedObject.useGalleryPhoto = true;
		this.feedObject.controlUrl = WHP.netcalls.popularCall;

        this.inited = true;
	},
	
	//std for each module control functions
	show: function (_q)
	{
		//get parametres
		var q = _q;
		if (!q)
			q = "0";		
		var params = q.split("/");
		
		//get offset param
		var offset = parseInt(params[0])*this.feedObject.imageLimit;
		if (isNaN(offset))
			offset = 0;			
		offset = Math.max(0, offset);		
		
		log("show");
		this.feedObject.show(offset);
	},
	hide: function ()
	{
		
	},

	onAuthChange: function (_auth)
	{
        if (_auth)
        {
            WHP.controller.navigateTo("timeline");
        }
	}
}



WHP.pages.whp = {
	//controller parametres
	urlStr : "whp",
	title : "Redirect...",
	rndEnable : true,
	inited : false,
	
	mainObject : null,	
	feedObject : null,
	
			
	//init function
	init: function ()
	{
		this.mainObject = id$('whp');

        this.inited = true;
	},
	
	//std for each module control functions
	show: function (_q)
	{
		//get parametres
		var q = _q;
		if (!q)
			q = "0";		
		var params = q.split("/");

        if (params[0] == "signup_confirmed")
        {
            WHP.controller.navigateTo(WHP.pages.findfriends.urlStr);

            return false;
        }

        if (params[0] == "signup_confirm_failed")
        {
            WHP.controller.showErrorPage();
            return false;
        }

        //http://whptest.weheartpics.com/whp/changepass/?code=aa6c0834be6328dc5a919854f2fbc864&login=h718442@rppkn.com
        if (params[0] == "changepass")
        {
            log("code = ["+params[1]+"]");
            WHP.pages.setpassword.code = params[1];
            WHP.controller.navigateTo(WHP.pages.setpassword.urlStr);
            return false;
        }

        if (params[0] == "signup_confirm_failed")
        {
            log("PW FILED!2");
            WHP.controller.showErrorPage(5);
            return false;
        }

        if (params[0] == "password_reset_failed")
        {
            log("PW FILED!");
            WHP.controller.showErrorPage(4);
            return false;
        }





        WHP.controller.navigateTo("timeline");
	},
	hide: function ()
	{
		
	},

	onAuthChange: function (_auth)
	{
	}
}



WHP.opengraph = {
    makeLikeAction : function(_photoId)
    {
        if (!WHP.settings.useOpenGraph)
            return false;
        //FB.api('/me/weheartpics:like', 'post', { photo : WHP.links.getPhotoLink(_photoId)}, function(response) {
        FB.api('/me/weheartpics:like', 'post', { photo : "http://weheartpics.com/photo/"+_photoId+"/"}, function(response) {
            log(response);
        });

    },

    makeFolowAction : function(_userId)
    {
        if (!WHP.settings.useOpenGraph)
            return false;
        //FB.api('/me/weheartpics:follow', 'post', { user : WHP.links.getUserProfileLink(_userId) }, function(response) {
        setTimeout(bind(function(){
        FB.api('/me/weheartpics:follow', 'post', { user : "http://weheartpics.com/user/"+_userId+"/" }, function(response) {
            log(response);
        });
        },this),100);
    },

    makeCommentAction : function(_photoId)
    {
        if (!WHP.settings.useOpenGraph)
            return false;
        //FB.api('/me/weheartpics:follow', 'post', { user : WHP.links.getUserProfileLink(_userId) }, function(response) {
        setTimeout(bind(function(){
            FB.api('/me/weheartpics:comment', 'post', { photo : "http://weheartpics.com/photo/"+_photoId+"/" }, function(response) {
                log(response);
            });
        },this),100);
    }
}


WHP.pages.getstarted = {
	//controller parametres
	urlStr : "getstarted",
	title : "Get started",
	rndEnable : false,
	inited : false,
	
	mainObject : null,	
	feedObject : null,

    error_meassage : null,

    mail_input : null,
    pw_input : null,
    proceedButton : null,


    active : false,

    errorMessageTimeout : -1,
	
			
	//init function
	init: function ()
	{
		this.mainObject = id$('getstarted');
        this.error_meassage = $(this.mainObject).find(".form_error_message");

        var inputs = $(this.mainObject).find(".form_input_field");
        this.mail_input = $(inputs[0]);
        this.pw_input = $(inputs[1]);
        this.proceedButton = $(this.mainObject).find(".form_confirm_button");
        this.proceedButton.click( bind(this.formProceed, this) );

        this.inited = true;
	},
	
	//std for each module control functions
	show: function (_q)
	{
        this.active = true;
        this.reset();
        WHP.controller.showCanvas();
	},

	hide: function ()
	{
        this.active = false;
	},

    reset : function()
    {
        this.mail_input.val("");
        this.pw_input.val("");
    },

    formProceed : function()
    {
        //check valid email
        var email =  this.mail_input.val();
        var password = this.pw_input.val();

        if (!validateEmail(email))
        {
            this.showErrMsg("Doesn't look like a valid email");
            this.mail_input.focus();
            return false;
        }


        if (password.length<6)
        {
            this.showErrMsg("Please use at least 6 characters");
            this.pw_input.focus();
            return false;
        }

        if  (password.length>16)
        {
            this.showErrMsg("You can't use more than 16 characters");
            this.pw_input.focus();
            return false;
        }


        //pew set resend params
        if (!true)
        {
            WHP.pages.confirmation.resendMail = email;
            WHP.pages.confirmation.resendPw = password;
            WHP.controller.navigateTo("confirmation");
            return false;
        }

        $.ajax({
            url:WHP.netcalls.regCall,
            data : { r : Math.random(), login :  email, passw : password },
            timeout:WHP.netTimeOut,
            method : "POST",
            success:bind(this.onRegOk, this),
            error:bind(this.onRegFail, this)
        });


        return false;
    },

    showErrMsg : function(_txt)
    {
        this.error_meassage.text(_txt);
        this.hideMsg();
    },

    onRegOk : function(response)
    {
        var resp = getObjectJson(response);
        if (resp.error)
        {
            if (resp.error.code!="API_PendingConfirmation")
            {
                if (resp.error.code == "API_AlreadyInUse")
                {
                    this.showErrMsg("This email already registered");
                    this.mail_input.focus();
                    return false;
                }
                this.showErrMsg("Something went wrong");
                this.mail_input.focus();
                return false;
            }
        }


        //check pending
        var pending = resp.state == "PENDING_CONFIRMATION";
        var errorPending = false;
        if (resp.error)
        if (resp.error.code == "API_PendingConfirmation")
            errorPending = true;
        pending = pending || errorPending;
        if (pending)
        {
            WHP.pages.confirmation.resendMail = this.mail_input.val();
            WHP.pages.confirmation.resendPw = this.pw_input.val();
            WHP.controller.navigateTo("confirmation");
            return false;
        }

        //
        log("Normal reg");
        WHP.auth.STD.onData(resp, true);
        WHP.controller.navigateTo("findfriends");
    },

    onRegFail : function(e)
    {
        this.showErrMsg("Something went wrong");
        //404???
    },

    hideMsg : function()
    {
       if (this.errorMessageTimeout!=-1)
            clearTimeout(this.errorMessageTimeout);
       this.errorMessageTimeout = setTimeout(bind(function() { this.error_meassage.text(""); this.errorMessageTimeout = -1; }, this),2000);
    },



	onAuthChange: function (_auth)
	{
        if (!this.active)
            return false;

        if (_auth)
            WHP.controller.navigateTo(WHP.controller.getMainPage().urlStr);
	}
};



WHP.pages.confirmation = {
    //controller parametres
    urlStr : "confirmation",
    title : "Confirmation",
    inited : false,
    rndEnable : false,

    mainObject : null,

    error_meassage : null,

    resendMail : "",
    resendPw : "",
    resendCount : 0,

    errorMessageTimeout : -1,

    init: function ()
    {
        this.mainObject = id$('confirmation');
        this.resendButton =  $(this.mainObject).find(".form_confirm_button");
        this.resendButton.click(bind(this.resendFunc, this));

        this.error_meassage = $(this.mainObject).find(".form_error_message");

        this.inited = true;
    },

    hideMsg : function()
    {
        if (this.errorMessageTimeout!=-1)
            clearTimeout(this.errorMessageTimeout);
        this.errorMessageTimeout = setTimeout(bind(function() { this.error_meassage.text(""); this.errorMessageTimeout = -1; }, this),2000);
    },

    showErrMsg : function(_txt)
    {
        this.error_meassage.text(_txt);
        this.hideMsg();
    },

    //std for each module control functions
    resendFunc : function()
    {

        log("resend with =["+this.resendMail+"] ["+this.resendPw+"]");
        $.ajax({
            url:WHP.netcalls.resendCall,
            data : { r : Math.random(), login :  this.resendMail, passw : this.resendPw },
            timeout:WHP.netTimeOut,
            method : "POST",
            success:bind(this.resendOk, this),
            error:bind(this.resendFail, this)
        });
    },

    resendOk : function(response)
    {
        var resp = getObjectJson(response);
        if (resp.error)
        {
            log("WHP/registration : error while loading page data! Err =["+response+"]");
            if (resp.error.code == "API_Rejected")
            {
                this.showErrMsg("Too many tries");
            }else if (resp.error.code == "API_ObjectNotFound")
            {
                this.showErrMsg("User wasnt found");
            }
            return false;
        }

        resendCount++;
        if (resp.status == "OK")
        {
            //confirmation
            if (resp.state == "PENDING_CONFIRMATION")
            {
                //change  message?
            }
            return false;
        }



        log("resendOK");
        log(resp);
    },

    resendFail : function(e)
    {
        this.showErrMsg("Something went wrong");
    },

    show: function (_q)
    {
        if ((WHP.auth.status) || (this.resendMail.length ==0) || (this.resendPw.length == 0))
        {
            WHP.controller.showErrorPage();
        }

        log("1Show find friends");
        WHP.controller.showCanvas();
        log("2Show find friends");
        log("Resend to = ["+this.resendMail+"]");
        this.resendCount = 0;
    },

    hide: function ()
    {

    },

    onAuthChange: function (_auth)
    {
        if (_auth)
            WHP.controller.navigateTo(WHP.controller.getMainPage().urlStr);
    }
}





WHP.pages.findfriends = {
    //controller parametres
    urlStr : "findfriends",
    title : "Connect with friends",
    inited : false,
    rndEnable : false,

    mainObject : null,

    facebookBtn : null,
    fbLinked : false,
    twitterBtn : null,
    twLinked : false,


    activeToken : false,
    curWind : null,



    init: function ()
    {
        this.mainObject = id$('findfriends');

        this.facebookBtn = $(this.mainObject).find(".social_link_fb_0");
        this.facebookBtn.click(bind(this.linkFb, this));
        this.twitterBtn = $(this.mainObject).find(".social_link_tw_0");
        this.twitterBtn.click(bind(this.linkTw, this));

        this.error_meassage = $(this.mainObject).find(".form_error_message");


        var btnNext = $(this.mainObject).find(".form_confirm_button");
        btnNext.click(bind(function(){
            WHP.controller.navigateTo(WHP.controller.getMainPage().urlStr);
        }, this));



        this.inited = true;
    },




    //twitter
    linkTw : function()
    {
        if (this.twLinked)
            return false;

        WHP.pages.settings.linker.TW.showErrMsg = bind(this.showErrMsg,this);
        WHP.pages.settings.linker.TW.onLink = bind(this.linkTwCallback,this);
        WHP.pages.settings.linker.TW.linkTw();
    },

    linkTwCallback : function(e)
    {
        setClass(this.twitterBtn, "social_link_tw_1");
        this.twLinked = true;
    },




    //facebook
    linkFb : function()
    {
        if (this.fbLinked)
            return false;

        //set up callbacks
        WHP.pages.settings.linker.FB.showErrMsg = bind(this.showErrMsg,this);
        WHP.pages.settings.linker.FB.onLink = bind(this.linkFbCallback,this);
        WHP.pages.settings.linker.FB.linkFb();
    },

    linkFbCallback : function(e)
    {
        setClass(this.facebookBtn, "social_link_fb_1");
        this.fbLinked = true;
    },


    hideMsg : function()
    {
        if (this.errorMessageTimeout!=-1)
            clearTimeout(this.errorMessageTimeout);
        this.errorMessageTimeout = setTimeout(bind(function() { this.error_meassage.text(""); this.errorMessageTimeout = -1; }, this),2000);
    },

    showErrMsg : function(_txt)
    {
        this.error_meassage.text(_txt);
        this.hideMsg();
    },


    //std for each module control functions
    show: function (_q)
    {
        if (!WHP.auth.status)
        {
            WHP.controller.showErrorPage();
        }

        log("1Show find friends");
        WHP.controller.showCanvas();
        log("2Show find friends");

        log("SETTINGS SHOW FINDFRIENDS");
        log(WHP.settings+" "+typeof(WHP.settings.social));
        log(WHP.settings+" "+(WHP.settings.social !== null)+" "+(WHP.settings.social != null)+" "+WHP.settings.social);

        if (WHP.settings.social)
        {
            log(typeof(WHP.settings.social.twitter));
            if (WHP.settings.social.twitter)
            {
                log("LINK TW");
                this.linkTwCallback();
            }
            if (WHP.settings.social.facebook)
            {
                log("LINK FB");
                this.linkFbCallback();
            }
        }

    },

    hide: function ()
    {

    },

    onAuthChange: function (_auth)
    {

    }
}



//http://whptest.weheartpics.com/api/confirm/preset/?id=5685&code=eb1d7915b0fee32c9f5ae0c2bf0b7de9
WHP.pages.setpassword = {
    //controller parametres
    urlStr : "setpassword",
    title : "Set new password",
    inited : false,
    rndEnable : false,

    proceedButton : false,
    mail_input : null,

    mainObject : null,
    error_meassage : null,

    errorMessageTimeout : -1,

    state0 : null,
    state1 : null,

    code : "",

    init: function ()
    {
        this.mainObject = id$('setpassword');

        this.mail_input = $(this.mainObject).find(".form_input_field");

        this.mail_input.keypress(bind(function(e)
        {
            var password = this.mail_input.val();
            if  (password.length>=16)
            {
                this.showErrMsg("You can't use more than 16 characters");
            }

            if (e.keyCode == 13){this.formProceed();}
        },this));


        this.proceedButton = $(this.mainObject).find(".form_confirm_button");
        this.proceedButton.click( bind(this.formProceed, this) );

        this.error_meassage = $(this.mainObject).find(".form_error_message");

        var states = $(this.mainObject).find(".type");
        this.state0 = $(states[0]);
        this.state1 = $(states[1]);


        this.inited = true;
    },

    formProceed : function()
    {
        var email =  this.mail_input.val();

        if (email.length<6)
        {
            this.showErrMsg("Please use at least 6 characters");
            this.mail_input.focus();
            return false;
        }

        if  (email.length>16)
        {
            this.showErrMsg("You can't use more than 16 characters");
            this.mail_input.focus();
            return false;
        }


        $.ajax({
            url:WHP.netcalls.setPwCall,
            data : { r : Math.random(), passw : email, code : this.code },
            timeout:WHP.netTimeOut,
            success:bind(this.resendOk, this),
            error:bind(this.resendFail, this)
        });
    },

    resendOk : function(response)
    {
        var resp = getObjectJson(response);
        if (resp.error)
        {
            WHP.controller.showErrorPage();
            return false;
        }

        this.code = "";
        this.setState(1);
    },

    resendFail : function(e)
    {
        this.code = "";
        this.showErrMsg("Something went wrong");
    },


    //std for each module control functions
    show: function (_q)
    {
        log("1Show find friends");
        WHP.controller.showCanvas();
        log("2Show find friends");
        this.reset();

        if (this.code == "")
            WHP.controller.navigateTo(WHP.controller.getMainPage().urlStr);
    },


    showErrMsg : function(_txt)
    {
        this.error_meassage.text(_txt);
        this.hideMsg();
    },

    hideMsg : function()
    {
        if (this.errorMessageTimeout!=-1)
            clearTimeout(this.errorMessageTimeout);
        this.errorMessageTimeout = setTimeout(bind(function() { this.error_meassage.text(""); this.errorMessageTimeout = -1; }, this),2000);
    },


    setState : function(_state)
    {
        if (_state == 0)
        {
            this.state0.css({ display : ''});
            this.state1.css({ display : 'none'});
        }else{
            this.state1.css({ display : ''});
            this.state0.css({ display : 'none'});
        }
    },

    reset : function()
    {
        this.setState(0);
        this.mail_input.val("");
    },

    hide: function ()
    {

    },

    onAuthChange: function (_auth)
    {
    }
}




WHP.pages.resendpw = {
    //controller parametres
    urlStr : "reset",
    title : "Reset password",
    inited : false,
    rndEnable : false,

    proceedButton : false,
    mail_input : null,

    mainObject : null,
    error_meassage : null,

    errorMessageTimeout : -1,

    state0 : null,
    state1 : null,

    init: function ()
    {
        this.mainObject = id$('reset');

        this.mail_input = $(this.mainObject).find(".form_input_field");
        this.proceedButton = $(this.mainObject).find(".form_confirm_button");
        this.proceedButton.click( bind(this.formProceed, this) );

        this.error_meassage = $(this.mainObject).find(".form_error_message");

        var states = $(this.mainObject).find(".type");
        this.state0 = $(states[0]);
        this.state1 = $(states[1]);


        this.inited = true;
    },

    formProceed : function()
    {
        var email =  this.mail_input.val();

        if (!validateEmail(email))
        {
            this.showErrMsg("Doesn't look like a valid email");
            this.mail_input.focus();
            return false;
        }

        log("RESET!");

        $.ajax({
            url:WHP.netcalls.resetPwCall,
            data : { r : Math.random(), login :  email },
            timeout:WHP.netTimeOut,
            success:bind(this.resendOk, this),
            error:bind(this.resendFail, this)
        });
    },

    resendOk : function(response)
    {
        var resp = getObjectJson(response);
        if (resp.error)
        {
            if ((resp.error.code == "API_Rejected") || (resp.error.code == "API_BadParams"))
            {
                this.showErrMsg("No user with this email");
                this.mail_input.focus();
            }else{
                WHP.controller.showErrorPage();
            }
            return false;
        }

        this.setState(1);

    },

    resendFail : function(e)
    {
        this.showErrMsg("Something went wrong");
    },


    //std for each module control functions
    show: function (_q)
    {
        log("1Show find friends");
        WHP.controller.showCanvas();
        log("2Show find friends");
        this.reset();
    },


    showErrMsg : function(_txt)
    {
        this.error_meassage.text(_txt);
        this.hideMsg();
    },

    hideMsg : function()
    {
        if (this.errorMessageTimeout!=-1)
            clearTimeout(this.errorMessageTimeout);
        this.errorMessageTimeout = setTimeout(bind(function() { this.error_meassage.text(""); this.errorMessageTimeout = -1; }, this),2000);
    },


    setState : function(_state)
    {
        if (_state == 0)
        {
            this.state0.css({ display : ''});
            this.state1.css({ display : 'none'});
        }else{
            this.state1.css({ display : ''});
            this.state0.css({ display : 'none'});
        }
    },

    reset : function()
    {
        this.setState(0);
        this.mail_input.val("");
    },

    hide: function ()
    {

    },

    onAuthChange: function (_auth)
    {
        if (_auth)
            WHP.controller.navigateTo(WHP.controller.getMainPage().urlStr);
    }
}




WHP.pages.settings = {
    //controller parametres
    urlStr : "settings",
    title : "Settings",
    rndEnable : false,
    inited : false,


    appSettings : {
        useOpenGraph : false,
        login : null,
        social : null
    },

    mainObject : null,

    opengraphSwitcher : null,
    linkerFBSwitcher : null,
    linkerTWSwitcher : null,

    window1 : null,
    button1 : null,
    button2 : null,
    button3 : null,

    window2 : null,


    prelogin : "",

	init : function()
    {
        this.mainObject = id$('settings');

        var lines = $(this.mainObject).find(".settings_line");

        this.opengraphSwitcher = $(lines[0]);
        this.opengraphSwitcher.switcher = new Switcher(this.opengraphSwitcher.find(".settings_switcher_0"));
        this.opengraphSwitcher.state = false;
        this.opengraphSwitcher.click(bind(this.ogClick,this));

        this.linkerFBSwitcher = $(lines[1]);
        this.linkerFBSwitcher.switcher = new Switcher(this.linkerFBSwitcher.find(".settings_switcher_0"));
        this.linkerFBSwitcher.state = false;
        this.linkerFBSwitcher.click(bind(this.linkerFBClick,this));

        this.linkerTWSwitcher = $(lines[2]);
        this.linkerTWSwitcher.switcher = new Switcher(this.linkerTWSwitcher.find(".settings_switcher_0"));
        this.linkerTWSwitcher.state = false;
        this.linkerTWSwitcher.click(bind(this.linkerTWClick,this));

        var tables = $(this.mainObject).find("table");









        //set login and password
        this.window1 = $("#set_login_pw");
        this.window1.activeSet = false;
        this.window1.css({ position : 'fixed' });
        this.window1.click(bind(function(event) {
            event.stopPropagation();
        }, this));
        this.window1.errorMessageTimeout = -1;
        this.window1.error_meassage = this.window1.find(".form_error_message");
        this.window1.showErrMsg = bind(function(_txt)
            {
                this.error_meassage.text(_txt);
                this.hideMsg();
            }
        ,this.window1);
        this.window1.hideMsg = bind(function()
            {
                if (this.errorMessageTimeout!=-1)
                    clearTimeout(this.errorMessageTimeout);
                this.errorMessageTimeout = setTimeout(bind(function() {  this.error_meassage.text(""); this.error_meassage.errorMessageTimeout = -1; }, this),2000);
            }
        ,this.window1);
        this.window1.proceedBtn = this.window1.find(".form_confirm_button");
        this.window1.proceedBtn.click(bind(this.setLoginPass, this));

        var inputs = this.window1.find(".form_input_field_sign");
        this.window1.input_mail = $(inputs[0]);
        this.window1.input_mail.keypress(bind(function(e)
        {
            if (e.keyCode == 13)
            {
                this.setLoginPass();
            }

        },this));

        this.window1.input_pass = $(inputs[1]);
        this.window1.input_pass.keypress(bind(function(e)
        {
            if (e.keyCode == 13)
            {
                this.setLoginPass();
            }

            if  (this.window1.input_pass.val().length>=16)
            {
                this.window1.showErrMsg("You can't use more than 16 characters!");
            }

        },this));






        this.window2 = $("#set_login");

        var pages =  this.window2.find(".login_page");
        this.window2.page1 = $(pages[0]);
        this.window2.page2 = $(pages[1]);


        this.window2.page1.input_pass = this.window2.page1.find(".form_input_field_sign");
        this.window2.page1.proceedBtn = this.window2.page1.find(".form_confirm_button");
        this.window2.page1.error_meassage = this.window2.page1.find(".form_error_message");
        this.window2.page1.errorMessageTimeout = -1;
        this.window2.page1.hideMsg = bind(this.hideMsg, this.window2.page1);
        this.window2.page1.showErrMsg = bind(this.showErrMsg, this.window2.page1);
        this.window2.page1.input_pass.keypress(bind(function(e)
        {
            if (e.keyCode == 13)
            {
                this.applyForm();
            }

        },this.window2.page1));
        this.window2.page1.proceedBtn.click(bind(function(e){
            this.window2.page1.applyForm();
        },this));
        this.window2.page1.applyForm = bind(function(e)     {
            var a = this.window2.page1;
            var password =  a.input_pass.val();




            //need call
            $.ajax({
                url:WHP.netcalls.confirmPwCall,
                data : { r : Math.random(), passw : password },
                timeout:WHP.netTimeOut,
                success:bind(this.onPwConfirm, this),
                error:bind(this.onPwConfirmErr, this)
            });


        }, this);




        this.window2.page2.input_mail = this.window2.page2.find(".form_input_field_sign");
        this.window2.page2.proceedBtn = this.window2.page2.find(".form_confirm_button");
        this.window2.page2.error_meassage = this.window2.page2.find(".form_error_message");
        this.window2.page2.errorMessageTimeout = -1;
        this.window2.page2.code = "";
        this.window2.page2.hideMsg = bind(this.hideMsg, this.window2.page2);
        this.window2.page2.showErrMsg = bind(this.showErrMsg, this.window2.page2);

        this.window2.page2.input_mail.keypress(bind(function(e)
        {
            if (e.keyCode == 13)
            {
                this.applyForm();
            }

        },this.window2.page2));
        this.window2.page2.proceedBtn.click(bind(function(e){
            this.window2.page2.applyForm();
        },this));
        this.window2.page2.applyForm = bind(function(e)     {
            var a = this.window2.page2;
            var email =  a.input_mail.val();



            if (!validateEmail(email))
            {
                a.showErrMsg("Doesn't look like a valid email!");
                a.input_mail.focus();
                return false;
            }

            a.prelogin = email;


            //this.onLoginConfirm();
            //return false;

            //need call
            $.ajax({
                url:WHP.netcalls.changeLoginCall,
                data : { r : Math.random(), login : email, code : this.window2.page2.code },
                timeout:WHP.netTimeOut,
                success:bind(this.onLoginConfirm, this),
                error:bind(this.onLoginConfirmErr, this)
            });


        }, this);
        this.window2.page2.prelogin = "";

        ///



        this.window2.css({ position : 'fixed' });
        this.window2.timer = new Timer(1000/30, 18);
        this.window2.timer.onTimerEvent = bind(function(e)
        {
            var A = e.currentCount/e.repeatCount;
            var B = Math.sin(A*Math.PI*0.5);
            var s = 260;
            this.page1.css({ left : -B*s+"px"});
            this.page2.css({ left : (1-B)*s+"px"});
            if (!browser.ie)
            {
               setAlpha(this.page1, Math.max(0,1-2*A));
            }

        },this.window2);
        this.window2.setState2 = bind(function()
        {
            this.timer.reset();
            this.timer.start();
        },this.window2);
        this.window2.setState1 = bind(function()
        {
            this.page1.css({ left : "0px"});
            this.page2.css({ left : "260px"});
            if (!browser.ie)
            {
                setAlpha(this.page1, 1.0);
            }
        },this.window2);






        //set login and pw
        this.button1 =  $(tables[2]).find(".settings_line");
        this.button1.click(bind(this.clickSetPwLogin,this));


        //set pw
        var lines = $(tables[1]).find(".settings_line");
        this.button2 = $(lines[0]);
        this.button2.click(bind(this.clickLogin, this));
        this.button3 = $(lines[1]);
        this.button3.click(bind(this.clickPassword, this));

        this.inited = true;
    },

    onLoginConfirmErr : function(e)
    {
        this.window2.page2.showErrMsg("Something went wrong");
    },

    onLoginConfirm : function(response)
    {
        var resp = getObjectJson(response);
        if (resp)
        if (resp.error)
        {
            if (resp.error.code == "API_AlreadyInUse")
            {
                this.window2.page2.showErrMsg("This email already registered");
                return false;
            }
            this.window2.page2.showErrMsg("Something went wrong");
            return false;
        }

        this.appSettings.login = this.window2.page2.prelogin;
        this.setView();
        this.hideWindow2();

    },


    onPwConfirm : function(response)
    {
        var resp = getObjectJson(response);
        if (resp)
        if (resp.error)
        {
            if ((resp.error.code == "API_Rejected") || (resp.error.code == "API_BadParams"))
            {
                this.window2.page1.showErrMsg("Wrong password!");
                this.window2.page1.input_pass.focus();
                return false;
            }
            this.window2.page1.showErrMsg("Something went wrong!");
            return false;
        }

        this.window2.page2.code = resp.code;
        this.window2.setState2();
        this.window2.page2.input_mail.focus();
    },

    onPwConfirmErr : function(e)
    {
        this.window2.page1.showErrMsg("Something went wrong!");
    },

    clickLogin : function(e)
    {
        this.window2.css({display:"block"});
        WHP.main_fader.show();

        //positions
        var scrollTop = getScrollTop();


        if (browser.ie)
        {
            this.window2.css({ position : 'absolute' });
            this.window2.css({ top : (scrollTop + (WHP.screenH - this.window2.height())*0.5 )+'px', left : (WHP.screenWl-285)*0.5 +'px' });
        }else
            this.window2.css({ top : (WHP.screenH - this.window2.height())*0.5 +'px', left : (WHP.screenWl-285)*0.5 +'px' });

        this.window2.page2.input_mail.val("");
        this.window2.page1.input_pass.val("");
        this.window2.setState1();
        this.window2.page1.input_pass.focus();

        return cancelEvent(e);
    },


    hideMsg : function()
    {
        if (this.errorMessageTimeout!=-1)
            clearTimeout(this.errorMessageTimeout);
        this.errorMessageTimeout = setTimeout(bind(function() { this.error_meassage.text(""); this.errorMessageTimeout = -1; }, this),2000);
    },

    showErrMsg : function(_txt)
    {
        this.error_meassage.text(_txt);
        this.hideMsg();
    },





    hideWindow2 : function()
    {
        if (this.window2.css("display") == 'none')
            return false;

        log("hideWindow2");
        this.window2.css({display:"none"});
        WHP.main_fader.hide();
    },



    clickPassword : function(e)
    {
        $.ajax({
            url:WHP.netcalls.setPwSettingsCall,
            data : { r : Math.random(), login :  this.appSettings.login },
            timeout:WHP.netTimeOut,
            success:bind(this.onpwResponse, this),
            error:bind(this.onErrorMessage, this)
        });
    },

    onErrorMessage : function(response)
    {
        WHP.popup_message.showAlert("Something went wrong!");
    },

    onpwResponse : function(response)
    {
        var resp = getObjectJson(response);
        if (resp.error)
        {
            if (!WHP.errors.hasNetError(resp))
            {
                WHP.controller.showErrorPage();
            }
            return false;
        }

        WHP.popup_message.showAlert("We have sent instructions to your email.", null, "/gui/mail_ico.png");
    },


    setLoginPass : function(e)
    {
        if (this.window1.activeSet)
            return false;

        var email =  this.window1.input_mail.val();
        var password = this.window1.input_pass.val();

        if (!validateEmail(email))
        {
            this.window1.showErrMsg("Doesn't look like a valid email!");
            this.window1.input_mail.focus();
            return false;
        }


        if (password.length<6)
        {
            this.window1.showErrMsg("Please use at least 6 characters!");
            this.window1.input_pass.focus();
            return false;
        }

        if  (password.length>16)
        {
            this.window1.showErrMsg("You can't use more than 16 characters!");
            this.window1.input_pass.focus();
            return false;
        }


        //pew set resend params
        if (!true)
        {
            WHP.pages.confirmation.resendMail = email;
            WHP.pages.confirmation.resendPw = password;
            WHP.controller.navigateTo("confirmation");
            return false;
        }

        this.prelogin = email;
        this.window1.activeSet = true;
        $.ajax({
            url:WHP.netcalls.setLogPwCall,
            data : { r : Math.random(), login :  email, passw : password, pass : password },
            timeout:WHP.netTimeOut,
            method : "POST",
            success:bind(this.onsetPWLGNOK, this),
            error:bind(this.onsetPWLGNFail, this)
        });



        return cancelEvent(e);
    },


    onsetPWLGNOK : function(response)
    {
        this.window1.activeSet = false;
        var resp = getObjectJson(response);
        if (resp.error)
        {
            if (resp.error.code == "API_AlreadyInUse")
            {
                this.window1.showErrMsg("This email already registered!");
                this.window1.input_mail.focus();
                return false;
            }
            this.window1.showErrMsg("Something went wrong!");
            this.window1.input_mail.focus();
            return false;
        }

        this.hideWindow1();
        this.appSettings.login = this.prelogin;
        this.setView();

    },

    onsetPWLGNFail : function(e)
    {
        this.window1.activeSet = false;
        this.showErrMsg("Something went wrong!");
    },



    linkerFBClick:function(e)
    {
        var fbConnected = false;
        if (WHP.settings.social)
        if (WHP.settings.social.facebook)
            fbConnected = true;

        if ( !fbConnected )
        {
            this.linker.FB.onLink = bind(this.linkerFB_link, this);
            this.linker.FB.showErrMsg = bind(WHP.popup_message.showAlert,WHP.popup_message);
            this.linker.FB.linkFb();
        }else{
            this.linker.FB.onUnlink = bind(this.linkerFB_unlink, this);
            this.linker.FB.showErrMsg = bind(WHP.popup_message.showAlert,WHP.popup_message);
            this.linker.FB.unlinkFb();
        }
    },

    linkerFB_link : function(e)
    {
        this.appSettings.social.facebook = true;
        this.setView();
    },

    linkerFB_unlink : function(resp)
    {


        delete this.appSettings.social.facebook;
        this.appSettings.useOpenGraph = false;
        this.setView();
    },



    linkerTWClick :function(e)
    {
        var linked = this.appSettings.social.twitter != null;
        if ( !linked )
        {
            this.linker.TW.onLink = bind(this.linkerTW_link, this);
            this.linker.TW.showErrMsg = bind(WHP.popup_message.showAlert,WHP.popup_message);
            this.linker.TW.linkTw();
        }else{
            this.linker.TW.onUnlink = bind(this.linkerTW_unlink, this);
            this.linker.TW.showErrMsg = bind(WHP.popup_message.showAlert,WHP.popup_message);
            this.linker.TW.unlinkTw();
        }
    },

    linkerTW_link : function(e)
    {
        this.appSettings.social.twitter = true;
        this.setView();
    },

    linkerTW_unlink : function(e)
    {
        delete this.appSettings.social.twitter;
        this.setView();
    },




    ogClick : function(e)
    {
        this.opengraphSwitcher.state = !this.opengraphSwitcher.state;


        if (this.opengraphSwitcher.state)
        {
            //FB.api('/me/permissions', bind(this.checkStatusCallback,this));
            this.linker.FB.showErrMsg = bind(WHP.popup_message.showAlert,WHP.popup_message);
            var madeLinkBefore = false;
            if (WHP.settings.social)
            if (WHP.settings.social.facebook)
                madeLinkBefore = true;

            log("madeLinkBefore = ["+madeLinkBefore+"]");
            if (!madeLinkBefore)
            {
                this.linkerFBClick();
            }else{
                WHP.auth.FB.loginOG(null, bind(function() {
                    FB.api('/me/permissions', bind(this.checkStatusCallback2,this));
                }, this));
            }

        }else{
            WHP.pages.settings.appSettings.useOpenGraph = false;

            this.setView();
            this.setSettings();
        }
    },


    checkStatusCallback2 : function(e)
    {
        log("CALL OG");
        log(e);
        var hasOGpermission = e.data[0].publish_actions == 1;
        if (hasOGpermission)
        {
            if (!this.appSettings.social.facebook)
            {
                this.appSettings.social.facebook = true;
            }
            WHP.pages.settings.appSettings.useOpenGraph = true;
            this.setSettings();
        }
    },









    show: function (_q)
    {
        //get parametres
        var q = _q;
        if (!q)
            q = "0";
        var params = q.split("/");

        if (!WHP.auth.status)
        {
            WHP.controller.navigateTo(WHP.controller.getMainPage().urlStr);
            return false;
        }




        this.getSettings();
    },

    getSettings : function()
    {


        $.ajax({
            url:WHP.netcalls.getSettingsCall,
            data : { r : Math.random() },
            timeout:WHP.netTimeOut,
            success:bind(this.dataSet, this),
            error:bind(this.onError, this)
        });
    },

    onData : function(resp)
    {
        var fb = null;
        var tw = null;
        if (resp.social)
        {
            fb = resp.social.facebook;
            tw = resp.social.twitter;
        }
        this.appSettings.useOpenGraph = (resp.settings.opengraph == true) && (fb);
        this.appSettings.social = resp.social;
        this.appSettings.login = resp.account.login;
    },

    dataSet : function(response)
    {
        log("Setup settings");
        var resp = getObjectJson(response);
        if (resp.error)
        {
            if (!WHP.errors.hasNetError(resp))
            {
                WHP.controller.showErrorPage();
            }
            return false;
        }

        this.onData(resp);




        this.setView();
        WHP.controller.showCanvas();
    },

    onError : function(resp)
    {
        WHP.controller.showErrorPage();
    },

    setSettings : function(e)
    {
        $.ajax({
            url:WHP.netcalls.setSettingsCall,
            data : { r : Math.random(), opengraph : this.appSettings.useOpenGraph },
            timeout : WHP.netTimeOut,
            success : bind(this.onSetCallback, this)
        });
    },
    onSetCallback : function(e)
    {
        this.setView();
    },


    setView : function()
    {
        this.opengraphSwitcher.state = this.appSettings.useOpenGraph;
        this.opengraphSwitcher.switcher.setView(this.opengraphSwitcher.state);

        log(this.appSettings.social);

        this.linkerFBSwitcher.state = this.appSettings.social.facebook != null;
        this.linkerFBSwitcher.switcher.setView(this.linkerFBSwitcher.state);

        this.linkerTWSwitcher.state = this.appSettings.social.twitter != null;
        this.linkerTWSwitcher.switcher.setView(this.linkerTWSwitcher.state);

        var tables = $(this.mainObject).find("table");
        if (this.appSettings.login)
        {
            $(tables[1]).css({display : ''});
            $(tables[2]).css({display : 'none'});

            var mail_label = $(tables[1]).find(".settings_label");
            $(mail_label[0]).text(this.appSettings.login);
        }else{
            $(tables[2]).css({display : ''});
            $(tables[1]).css({display : 'none'});
        }

    },

    hide: function ()
    {

    },


    clickSetPwLogin : function(e)
    {



        log("showWindow");
        this.window1.css({display:"block"});
        WHP.main_fader.show();

        //positions
        var scrollTop = getScrollTop();


        if (browser.ie)
        {
            this.window1.css({ position : 'absolute' });
            this.window1.css({ top : (scrollTop + (WHP.screenH - this.window1.height())*0.5 )+'px', left : (WHP.screenWl-285)*0.5 +'px' });
        }else
            this.window1.css({ top : (WHP.screenH - this.window1.height())*0.5 +'px', left : (WHP.screenWl-285)*0.5 +'px' });

        this.window1.input_mail.val("");
        this.window1.input_pass.val("");

        return cancelEvent(e);
    },

    hideWindow1 : function()
    {
        if (this.window1.css("display") == 'none')
            return false;

        log("hideWindow");
        this.window1.css({display:"none"});
        WHP.main_fader.hide();
    },











    linker : {
        FB : {
            showErrMsg : null,
            onLink : null,
            onUnlink : null,

            unlinkFb : function()
            {
                $.ajax({
                    url:WHP.netcalls.unlinkSocialCall,
                    data : { r : Math.random(), social : 'facebook' },
                    timeout: WHP.netTimeOut,
                    success:bind(this.fbUnlink, this),
                    error:bind(this.err, this)
                });
            },

            fbUnlink : function(response)
            {
                var resp = getObjectJson(response);
                if (resp.error)
                {
                    if (resp.error.code == "API_UnlinkLastAccount")
                    {
                        WHP.popup_message.showAlert("You can't unlink all accounts!");
                    }else{
                        WHP.popup_message.showAlert("Something went wrong!");
                    }
                    return false;
                }

                if (this.onUnlink)
                    this.onUnlink(resp);

            },



            linkFb : function()
            {

                FB.login(bind(this.onFBData, this), { scope:'publish_actions,publish_stream,user_photos,offline_access,email,user_birthday'});
            },

            onFBData: function(response)
            {
                if (response.status == "connected")
                {
                    log("Facebook : user was succesfully connected! :)");
                    var token = response.authResponse.accessToken;
                    if (token)
                    {
                        this.finalLinkFb(token);
                    }else{
                        log("Facebook : user was not connected! :(");
                    }
                }
            },


            finalLinkFb : function(_token)
            {
                $.ajax({
                    url:WHP.netcalls.linkSocialCall,
                    data : { r : Math.random(), social : 'facebook', access_token : _token },
                    timeout: WHP.netTimeOut,
                    success:bind(this.fbLink, this),
                    error:bind(this.err, this)
                });
            },


            fbLink : function(response)
            {
                var resp = getObjectJson(response);
                if (resp.error)
                {
                    if (resp.error.code == "API_AlreadyInUse")
                    {
                        log("ERR = [] = ["+this.showErrMsg+"]");
                        if (this.showErrMsg)
                            this.showErrMsg("This account is already linked with WeHeartPics!");
                    }else{
                        WHP.controller.showErrorPage();
                    }
                    return false;
                }

                if (this.onLink)
                    this.onLink(resp);

                if (!WHP.settings.social)
                    WHP.settings.social = {};
                WHP.settings.social.facebook = true;



                //get opengraph status
                FB.api('/me/permissions', bind(function(e)
                {
                    var hasOGpermission = e.data[0].publish_actions == 1;
                    if (hasOGpermission)
                    {
                        WHP.pages.settings.appSettings.useOpenGraph = true;
                        WHP.pages.settings.setView();
                    }
                },this));

            },

            err : function(e)
            {
                if (this.showErrMsg)
                    this.showErrMsg("Something went wrong!");
            }

        },
        TW : {
            showErrMsg : null,
            onLink : null,
            onUnlink : null,

            inited : false,
            jqxhr : null,
            requesttoken : null,
            req_count : 0,
            req_max : 10,
            preStatus : null,
            activeToken : false,
            curWind : null,


            unlinkTw : function()
            {
                $.ajax({
                    url:WHP.netcalls.unlinkSocialCall,
                    data : { r : Math.random(), social : 'twitter' },
                    timeout: WHP.netTimeOut,
                    success:bind(this.twUnlink, this),
                    error:bind(this.err, this)
                });
            },

            twUnlink : function(response)
            {
                var resp = getObjectJson(response);
                if (resp.error)
                {
                    if (resp.error.code == "API_UnlinkLastAccount")
                    {
                        WHP.popup_message.showAlert("You can't unlink all accounts!");
                    }else{
                        WHP.popup_message.showAlert("Something went wrong!");
                    }
                    return false;
                }

                if (this.onUnlink)
                    this.onUnlink(resp);
            },


            linkTw : function (e)
            {
                this.req_count = 0;
                this.curWind = openWindow2("Twitter link", 640, 480);
                this.getReqToken();
            },

            getReqToken : function()
            {
                this.activeToken = true;
                this.jqxhr = $.ajax({
                    url: WHP.netcalls.twReqTokenCall,
                    data : { r : Math.random() },
                    timeout : WHP.netTimeOut,
                    success: bind(this.onDataToken, this),
                    error: bind(this.onErrorToken, this)
                });
            },

            onDataToken: function(response, status, xhr)
            {
                this.activeToken = false;
                var resp = getObjectJson(response);

                if (resp.error)
                {
                    this.req_count++;
                }else{
                    this.req_count = 0;

                    if ( this.curWind )
                        this.curWind.location.href = "http://api.twitter.com/oauth/authorize?oauth_token="+resp.oauth_token;
                }
            },

            onErrorToken: function(response)
            {
                this.activeToken = false;
                var status = response['status'];

                if (status==0)
                {
                    //offline
                    log("WHP/auth/TW : OFFLINE mode!");
                }else{
                    this.getReqTokenAct();
                    this.req_count++;
                    log("WHP/auth/TW : error while getting twitter request token! Status = ["+status+"] Tries = ["+this.req_count+"]");
                }
            },


            finalLinkTw: function(_id, _token, _secret)
            {
                log("Final link twitter");
                $.ajax({
                    url:WHP.netcalls.linkSocialCall,
                    data : { r : Math.random(), social : 'twitter', access_token : _token, access_token_secret : _secret },
                    timeout: WHP.netTimeOut,
                    success:bind(this.onData, this),
                    error:bind(this.err, this)
                });
            },

            onData: function(response, status, xhr)
            {
                var resp = getObjectJson(response);
                if (resp.error)
                {
                    if (resp.error.code == "API_AlreadyInUse")
                    {
                        if (this.showErrMsg)
                            this.showErrMsg("This account is already linked with WeHeartPics!");
                    }else{
                        WHP.controller.showErrorPage();
                    }
                    return false;
                }


                if (!WHP.settings.social)
                    WHP.settings.social = {};
                WHP.settings.social.twitter = true;


                log("onLink");
                if (this.onLink)
                    this.onLink(resp);
            },


            err : function(e)
            {
                if (this.showErrMsg)
                    this.showErrMsg("Something went wrong!");
            }


        }
    }

}


WHP.settings = WHP.pages.settings.appSettings;




WHP.pages.story = {
	//controller parametres
	urlStr : "story",
	title : "Scenario",
	rndEnable : true,
	inited : false,
	
	mainObject : null,	
	feedObject : null,
	titleLabel : null,
    navLabel : null,

    labl1 : null,
    labl2 : null,
	
	storyId : 0,


    linkBack : false,
    linkBackRealBack : false,
    storyType : "",
    storyName : "",
    storyCat : 0,
			
	//init function
	init: function ()
	{
		this.mainObject = id$('story');
		this.feedObject = new whp_feed_proto();
		
		this.titleLabel = $(this.mainObject).find(".feed_name_labl2");

        this.labl1 = $(this.mainObject).find(".feed_name4");
        this.labl2 = $(this.mainObject).find(".feed_name8");
		
		var feed_cont = $(this.mainObject).find(".popular_photo_box");
		this.feedObject.init(feed_cont);	
		
		this.feedObject.changeUrl = true;
        this.feedObject.useGalleryPhoto = true;
		this.feedObject.callWasVote = WHP.netcalls.wasVoteCall;
        this.feedObject.hidePaginOnNull = false;
		this.feedObject.onLoadCall = bind(this.onloadCall,this);
	},
	
	//std for each module control functions
	show: function (_q)
	{
		//get parametres
		var q = _q;
		if (!q)
			q = "0";
					
		var params = q.split("/");
		var storyId = parseInt(params[0]);
		if (isNaN(storyId))
		{
			log("WHP/scenario : parametres error");
			this.storyId = null;
			WHP.controller.showErrorPage(2);
			return false;
		}
		this.storyId = storyId;
		
		//get offset param
		var offset = parseInt(params[1])*this.feedObject.imageLimit;
		if (isNaN(offset))
			offset = 0;			
		offset = Math.max(0, offset);

        if (this.linkBack)
        {
            this.linkBack = false;
            this.linkBackRealBack = true;
        }else{
            this.linkBackRealBack = false;
        }
		
		
		this.feedObject.urlPrefix = this.urlStr+"/"+this.storyId;
		this.feedObject.controlUrl = WHP.netcalls.storyInfoUrl+"?story="+this.storyId;
		this.feedObject.show(offset);
	},
	hide: function ()
	{
		
	},
	
	restore: function ()
	{
        if (WHP.controller.removedList.length>0)
        {
            this.show(this.storyId+"/");
        }else{
            WHP.controller.showCanvas();
        }
	},
	
	onloadCall : function(_resp)
	{
        var storyName = "";
        var navStr = "";

        this.storyType = _resp.story.type;
        if (this.storyType == "STORY")
        {
            this.labl1.css({ display : ''});
            storyName = "<span class='feed_name_labl2'>"+_resp.story.name+"</span>";
            this.storyName = _resp.story.name;

            navStr = "<a class='controls_link_text' style='font-size:26px;' href='"+WHP.links.getStoriesLink(_resp.story.storyset.storycat.id)+"'www>"+_resp.story.storyset.storycat.name+"</a>";
		}else if (this.storyType == "UNSORTED")
        {
            this.labl1.css({ display : ''});
            storyName = "<span class='feed_name_labl2'>"+_resp.story.storyset.name+"</span>";
            this.storyName = _resp.story.storyset.name;

            this.storyCat = _resp.story.storyset.storycat.id;

            navStr = "<a class='controls_link_text' style='font-size:26px;' href='"+WHP.links.getStoriesLink(_resp.story.storyset.storycat.id)+"'>"+_resp.story.storyset.storycat.name+"</a>";
        }else if (this.storyType == "DAILY")
        {
            this.labl1.css({ display : ''});
            storyName = "<span class='feed_name_labl2'>"+_resp.story.name+"</span>";
            this.storyName = _resp.story.name;

            navStr = "<a class='controls_link_text' style='font-size:26px;' href='"+WHP.links.getStoriesLinkDaily()+"'>Daily stories</a>";
        }else if (this.storyType == "PRIVATE")
        {
            this.labl1.css({ display : 'none'});
            storyName = "<a class='feed_name_labl2' href='"+WHP.links.getScenarioLink(_resp.story.id)+"'>PERSONAL PHOTOS</a>";
            this.storyName = "Personal photo";
        }else{
            this.labl1.css({ display : 'none'});
            storyName = "<span class='feed_name_labl2'>"+_resp.story.name+"</span>";
            this.storyName = _resp.story.name;
        }

        if (this.storyName.length>0)
        {
            this.storyName = this.storyName.charAt(0).toUpperCase() + this.storyName.slice(1);
        }


        this.setTitle();

		this.labl2.html(storyName);
        this.labl1.html(navStr);

		var linker = $(this.feedObject.pagingContainer).find(".feed_story_back");	
		linker.text("Back to stories").click(bind(this.linkerClick, this)).css({ cursor : 'pointer' });


        addIntelloLinks( this.labl1 );
	},


    setTitle : function()
    {
        this.title = this.storyName;
        WHP.controller.setTitle();
    },


    linkerClick: function (_auth)
    {
        log("this.linkBackRealBack = ["+this.linkBackRealBack+"]");
        if (this.linkBackRealBack)
        {
            history.back();
        }else{
            if (this.storyType == "DAILY")
            {
                WHP.controller.navigateTo( "stories/daily" );
            }else{
                WHP.controller.navigateTo( "stories/"+this.storyCat );
            }
        }
    },
	
	onAuthChange: function (_auth)
	{
		log("WHP/pages/scenario : on auth change to = ["+_auth+"]");
		this.feedObject.loadWasVote(_auth);
	}
}







WHP.pages.story = {
	//controller parametres
	urlStr : "story",
	title : "Scenario",
	rndEnable : true,
	inited : false,
	
	mainObject : null,	
	feedObject : null,
	titleLabel : null,
    navLabel : null,

    labl1 : null,
    labl2 : null,
	
	storyId : 0,


    linkBack : false,
    linkBackRealBack : false,
    storyType : "",
    storyName : "",
    storyCat : 0,
			
	//init function
	init: function ()
	{
		this.mainObject = id$('story');
		this.feedObject = new whp_feed_proto();
		
		this.titleLabel = $(this.mainObject).find(".feed_name_labl2");

        this.labl1 = $(this.mainObject).find(".feed_name4");
        this.labl2 = $(this.mainObject).find(".feed_name8");
		
		var feed_cont = $(this.mainObject).find(".popular_photo_box");
		this.feedObject.init(feed_cont);	
		
		this.feedObject.changeUrl = true;
        this.feedObject.useGalleryPhoto = true;
		this.feedObject.callWasVote = WHP.netcalls.wasVoteCall;
        this.feedObject.hidePaginOnNull = false;
		this.feedObject.onLoadCall = bind(this.onloadCall,this);
	},
	
	//std for each module control functions
	show: function (_q)
	{
		//get parametres
		var q = _q;
		if (!q)
			q = "0";
					
		var params = q.split("/");
		var storyId = parseInt(params[0]);
		if (isNaN(storyId))
		{
			log("WHP/scenario : parametres error");
			this.storyId = null;
			WHP.controller.showErrorPage(2);
			return false;
		}
		this.storyId = storyId;
		
		//get offset param
		var offset = parseInt(params[1])*this.feedObject.imageLimit;
		if (isNaN(offset))
			offset = 0;			
		offset = Math.max(0, offset);

        if (this.linkBack)
        {
            this.linkBack = false;
            this.linkBackRealBack = true;
        }else{
            this.linkBackRealBack = false;
        }
		
		
		this.feedObject.urlPrefix = this.urlStr+"/"+this.storyId;
		this.feedObject.controlUrl = WHP.netcalls.storyInfoUrl+"?story="+this.storyId;
		this.feedObject.show(offset);
	},
	hide: function ()
	{
		
	},
	
	restore: function ()
	{
        if (WHP.controller.removedList.length>0)
        {
            this.show(this.storyId+"/");
        }else{
            WHP.controller.showCanvas();
        }
	},
	
	onloadCall : function(_resp)
	{
        var storyName = "";
        var navStr = "";

        this.storyType = _resp.story.type;
        if (this.storyType == "STORY")
        {
            this.labl1.css({ display : ''});
            storyName = "<span class='feed_name_labl2'>"+_resp.story.name+"</span>";
            this.storyName = _resp.story.name;

            navStr = "<a class='controls_link_text' style='font-size:26px;' href='"+WHP.links.getStoriesLink(_resp.story.storyset.storycat.id)+"'>"+_resp.story.storyset.storycat.name+"</a>";
        }else if (this.storyType == "UNSORTED")
        {
            this.labl1.css({ display : ''});
            storyName = "<span class='feed_name_labl2'>"+_resp.story.storyset.name+"</span>";
            this.storyName = _resp.story.storyset.name;

            this.storyCat = _resp.story.storyset.storycat.id;

            navStr = "<a class='controls_link_text' style='font-size:26px;' href='"+WHP.links.getStoriesLink(_resp.story.storyset.storycat.id)+"'>"+_resp.story.storyset.storycat.name+"</a>";
        }else if (this.storyType == "DAILY")
        {
            this.labl1.css({ display : ''});
            storyName = "<span class='feed_name_labl2'>"+_resp.story.name+"</span>";
            this.storyName = _resp.story.name;

            navStr = "<a class='controls_link_text' style='font-size:26px;' href='"+WHP.links.getStoriesLinkDaily()+"'>Daily stories</a>";
        }else if (this.storyType == "PRIVATE")
        {
            this.labl1.css({ display : 'none'});
            storyName = "<a class='feed_name_labl2' href='"+WHP.links.getScenarioLink(_resp.story.id)+"'>PERSONAL PHOTOS</a>";
            this.storyName = "Personal photo";
        }else{
            this.labl1.css({ display : 'none'});
            storyName = "<span class='feed_name_labl2'>"+_resp.story.name+"</span>";
            this.storyName = _resp.story.name;
        }

        if (this.storyName.length>0)
        {
            this.storyName = this.storyName.charAt(0).toUpperCase() + this.storyName.slice(1);
        }


        this.setTitle();

		this.labl2.html(storyName);
        this.labl1.html(navStr);

		var linker = $(this.feedObject.pagingContainer).find(".feed_story_back");	
		linker.text("Back to stories").click(bind(this.linkerClick, this)).css({ cursor : 'pointer' });


        addIntelloLinks( this.labl1 );
	},


    setTitle : function()
    {
        this.title = this.storyName;
        WHP.controller.setTitle();
    },


    linkerClick: function (_auth)
    {
        log("this.linkBackRealBack = ["+this.linkBackRealBack+"]");
        if (this.linkBackRealBack)
        {
            history.back();
        }else{
            if (this.storyType == "DAILY")
            {
                WHP.controller.navigateTo( "stories/daily" );
            }else{
                WHP.controller.navigateTo( "stories/"+this.storyCat );
            }
        }
    },
	
	onAuthChange: function (_auth)
	{
		log("WHP/pages/scenario : on auth change to = ["+_auth+"]");
		//this.feedObject.loadWasVote(_auth);
	}
}







WHP.pages.timeline = {
	//controller parametres
	urlStr : "timeline",
	title : "Timeline",
	rndEnable : false,
	inited : false,
	
	mainObject : null,	
	timelineObject : null,

    restoreParams : null,
			
	//init function
	init: function ()
	{
		this.mainObject = id$('timeline');
		this.timelineObject = new whp_timeline_proto();
        var t = this.timelineObject;
		
		
		var tl_cont = $(this.mainObject).find(".timeline_box");
		t.controlUrl = WHP.netcalls.timelineGlobalCallUrl;
		t.prefix = this.urlStr;
		t.showEvents = true;
		t.controlCanvas = true;
		t.userObject = WHP.auth.userObject;
        t.parent = this;
        t.usePosRecalAfterRebuild = true;
        t.showEmpty = true;
		t.init(tl_cont);
        this.resetRestore();
	},

    onContentHeightChange : function(e)
    {
        if (this.restoreParams.setScroll)
        {
            window.scrollTo(0,this.restoreParams.scrollpos);
            WHP.menu.setShadow(this.restoreParams.scrollpos);
            this.restoreParams.setScroll = false;
        }
    },

    resetRestore : function()
    {
        this.restoreParams = {
            scrollpos : 0,
            setScroll : false,
            timelineRestoreResponse : null
        }
    },
	//std for each module control functions
    restore: function (e)
    {
        WHP.controller.showCanvas();

        if (WHP.controller.removedList.length>0)
        {
            log("REbuild");
            this.timelineObject.rebuildTimeline(WHP.controller.removedList, this.restoreParams);
        }else{
            log("restore = ["+this.restoreParams.scrollpos+"]");
            this.restoreParams.setScroll = true;

        }

        this.timelineObject.restore(e);

        if (false)
        if (this.restoreParams.timelineRestoreResponse)
        {
            this.timelineObject.onData(this.restoreParams.timelineRestoreResponse,  this.timelineObject.startPage);
            this.restoreParams.timelineRestoreResponse = null;
        }

    },

	show: function (_q)
	{
        if (!WHP.auth.status)
        {
            WHP.controller.navigateTo("popular/");
            return false;
        }

        log("TIMELINE");

        this.resetRestore();
		this.timelineObject.show(0);
	},
	hide: function()
	{
        this.restoreParams.scrollpos = getScrollTop();
        log("restorre pos = ["+this.restoreParams.scrollpos+"]");
		this.timelineObject.hide();


	}
}




whp_photolist_prototype = function () { return {
    //main nav
    position : 0,
    elements : [],

    //display elements
    rollover_plate : null,
    parent : null,
    active : false,

    //     net vars
    callUrl : "",
    userUrl : false,

    offset : 0,
    limit : 32,
    limit_left : 4,         //this more than next V
    limitStep : 28,
    preloadEdgeLimit : 2,
    total : 0,
    loadingActive : false,


    //while loading
    direction : 1,

    applyAction : false,
    nextPhoto : 0,


    init : function()
    {
        this.limitStep = this.limit-this.limit_left;
        this.rollover_plate.backward_button.click( bind( function() { this.setPosition(-1); }, this));
        this.rollover_plate.forward_button.click( bind( function() { this.setPosition(1); }, this));
        this.loadList.parent = this;
    },

    loadList : {
        parent : null,
        arr : null,
        active : false,
        nToLoad : 0,
        phace : 0,
        offset : 0,
        total : 0,

        startOffset : 0,


        loadImages : function(_offset, _start)
        {
            if (this.active)
                return false;

            this.arr = null;
            this.active = true;

            this.nToLoad = Math.min(this.parent.limitStep + this.parent.limit-this.parent.elements.length, this.parent.total);
            if (this.nToLoad < this.parent.limitStep)
                this.offset = 0
            else
                this.offset = _offset;

            this.startOffset = this.offset;
            this.phace = 0;

            log("this.nToLoad = ["+this.nToLoad+"]");

            log("0 Load offset = ["+this.offset+"] ["+this.nToLoad+"]");
            $.ajax({
                url:this.parent.callUrl,
                data : { offset : this.offset, limit : this.nToLoad, r : Math.random() },
                timeout:WHP.netTimeOut,
                success:bind(this.onData, this),
                error:bind(this.onError, this)
            });
        },
        onError : function(response)
        {
            this.active = false;
        },

        onData : function (response) {


            var resp = getObjectJson(response);
            if (resp.error) {
                return false;
            }

            //popular
            var pResp = resp.photos;
            var pList = resp.photos.list;
            var pTotal = resp.photos.total;

            this.total = pTotal;

            if (this.phace == 0)
            {

                this.nToLoad = Math.max(0, this.nToLoad - pList.length);
                log("RESULT p.length = [ "+pList.length+"] toload = ["+this.nToLoad+"]");
                this.arr = [];

                for (var i=0; i<pList.length; i++)
                    this.arr.push( { photo : pList[i], offset : this.offset+i });

                if (this.nToLoad == 0)
                {
                    this.active = false;
                    this.parent.appendData(this.arr);
                    return true;
                }

                this.offset = limitPos(this.offset + pList.length, this.parent.total);
                this.phace++;
                log("1 Load offset = ["+this.offset+"] ["+this.nToLoad+"]");
                $.ajax({
                    url:this.parent.callUrl,
                    data : { offset : this.offset, limit : this.nToLoad, r : Math.random() },
                    timeout:WHP.netTimeOut,
                    success:bind(this.onData, this),
                    error:bind(this.onError, this)
                });
                return true;
            }else{
                log("PHACE2");
                for (var i=0; i<pList.length; i++)
                    this.arr.push( { photo : pList[i], offset : this.offset+i });

                this.nToLoad = Math.max(0, this.nToLoad - pList.length);
                this.active = false;
                this.parent.appendData(this.arr);


            }
        }
    },

    setPosition : function(_N)
    {
        log("SETPOSITION = ["+_N+"]");
        var newPos = this.position+_N;

        this.applyAction = false;
        this.nextPhoto = 0;

        //have 2do
        if (!this.userUrl || (this.userUrl && (this.elements.length == this.total)))
        {
            //limited pos
            log("NOT LOADING ["+this.elements.length+"] ["+this.total+"]");
            this.position = limitPos(newPos, this.elements.length);
            //showPhoto
            this.setParentPhoto(this.position);
            return true;
        }

        var edge = false;
        if ( ((this.position<=this.preloadEdgeLimit) && (_N<0)) || ((this.position>=this.elements.length-this.preloadEdgeLimit) && (_N>0)))
        {
            if ((this.position==0) || (this.position==this.elements.length-1))
            {
                edge = true;
                this.applyAction = true;
            }


            var newOffset = this.offset;
            if (this.position<=this.preloadEdgeLimit)
            {
                newOffset = newOffset-this.limitStep;
                this.nextPhoto = -1;
                this.direction = -1;
            }else{
                newOffset = newOffset+this.elements.length;
                this.nextPhoto = 1;
                this.direction = 1;
            }
            newOffset = limitPos(newOffset, this.total);

            if (!this.loadList.active)
            {

                this.loadList.loadImages(newOffset);
            }
        }
        if (edge)
            return false;

        newPos =  Math.max(0, Math.min(this.elements.length-1, newPos));

        this.position = newPos;
        this.setParentPhoto(this.position);


        return true;
    },

    appendData : function(_arr)
    {
        this.total = this.loadList.total;

        var lengthDelt = this.limit - this.elements.length;

        if (this.total < this.limit)
        {
            log("STORY L < LIMIT! ["+this.total+" - "+this.limit+"]");
            this.elements = _arr;
            this.position = limitPos(this.offset+this.position);
            this.offset = 0;

        }else{
            if (this.direction>0)
            {
                this.elements.splice(0,_arr.length-lengthDelt);
                this.offset = this.loadList.startOffset - this.elements.length;
                this.elements = this.elements.concat(_arr);
                this.position = this.position-_arr.length;
            }else if (this.direction<0){
                this.elements.splice(this.elements.length-_arr.length+lengthDelt,_arr.length);
                this.elements = _arr.concat(this.elements);
                this.position = this.position+_arr.length;
                this.offset = this.loadList.startOffset;
            }
        }
        this.viewCheck();

        log("newL = ["+this.elements.length+"] ["+this.limit+"] +["+_arr.length+"]");

        if (this.applyAction)
        {
            //Move next
            this.setPosition(this.nextPhoto);
        }
    },

    onData : function (response) {
        this.loadingActive = false;

        var resp = getObjectJson(response);
        if (resp.error) {
            return false;
        }


        //popular
        var pResp = resp.photos;
        var pList = resp.photos.list;
        var pTotal = resp.photos.total;


        var newArr = [];
        for (var i = 0; i < pList.length; i++)
        {
            newArr.push({ photo : pList[i] });
        }

        var newArrL = newArr.length;

        if (this.newLoadType<0)
        {
            this.elements.splice(this.preloadL+1, newArrL);
            this.elements = $.merge( newArr, this.elements);

            this.position = this.position + newArrL;
            this.curOffset = this.newOffset;
        }else if (this.newLoadType>0){
            this.elements.splice(0,newArrL);
            this.elements = $.merge( this.elements, newArr);

            this.position = this.position - newArrL;
            this.curOffset = this.curOffset + newArrL;
        }


        this.viewCheck();
    },



    loadStartData : function()
    {
        this.offset = Math.max(0, this.offset-this.limit_left);
        this.loadingActive = true;

        $.ajax({
            url:this.callUrl,
            data : { offset : this.offset, limit : this.limit, r : Math.random() },
            timeout:WHP.netTimeOut,
            success:bind(this.onDataStart, this),
            error:bind(this.onError, this)
        });
    },


    onDataStart : function (response) {
        this.loadingActive = false;

        var resp = getObjectJson(response);
        if (resp.error) {
            return false;
        }

        //popular
        var pResp = resp.photos;
        var pList = resp.photos.list;
        var pTotal = resp.photos.total;

        ///check
        var found = false;
        this.total = pTotal;
        var Arr = [];
        for (var i = 0; i < pList.length; i++)
        {
            if (pList[i].id == this.elements[0].id)
            {
                Arr.push({ photo : this.elements[0], offset : this.offset+i +" X " });
                this.position = new Number(i);
                found = true;
            }else{
                Arr.push({ photo : pList[i], offset : this.offset+i +" X " });
            }
        }

        if (!found)
        {
            log("PhotoWasnt found!");
            Arr.splice(0,0,this.elements[0]);
            this.position = 0;
        }

        this.elements = Arr;
        this.viewCheck();
    },



    setParentPhoto : function(_pos)
    {
        //scrollTo comments
        var a = this.parent;
        a.scrollToComments = false;
        a.curPageId = this.elements[_pos].photo.id;
        a.curPageObject = this.elements[_pos];
        a.comments.clearComments();
        a.share.resetShare(true);
        setClass(this.parent.mainImage.image_cont, "photobig_image_container_0");
        a.createNewImage();

        a.mainImage.infoCont.css({ visibility : 'hidden'});
        a.mainImage.likeShadow.css({ visibility : 'hidden'});

        a.onData(this.parent.curPageObject);
        WHP.pages.photo.setHearts();
        this.viewCheck();

        setLinkReplace(WHP.links.getPhotoLink(this.elements[_pos].photo.id), null);
    },




    getCurPhotoPos : function()
    {
        if (this.userUrl)
            return limitPos(this.position + this.offset, this.total) ;
        return this.position;
    },

    getCurrentTotal : function()
    {
        if (this.userUrl)
            return this.total;
        return this.elements.length;
    },

    viewCheck : function()
    {
        var a = this.rollover_plate;
        a.move_label.html((this.getCurPhotoPos()+1)+"/"+this.getCurrentTotal());
    },

    checkDisplay : function ()
    {
        if (!this.userUrl)
            if (this.elements.length>1)
            {
                this.viewCheck();
                this.active = true;
            }else{
                this.active = false;
            }
    },


    setContentLink : function (_e, _pos, _call)
    {
        this.elements = [];

        this.elements.push(_e);

        this.viewCheck();
        this.active = true;
        this.userUrl = true;


        this.total = _pos;
        this.offset = _pos;
        this.callUrl = _call;



        this.loadStartData();
    },

    setContent : function (_e, _pos)
    {
        this.elements = _e;
        if (typeof(_pos)=='undefined')
            this.position = 0
        else
            this.position = _pos;

        this.viewCheck();


        if (this.elements.length>1)
        {
            this.active = true;
        }else{
            this.active = false;
        }

        this.curPhotoOffset = _pos;
        this.total = _e.length;
        this.userUrl = false;
    },

    clear : function ()
    {
        this.elements = [];
        this.rollover_plate.hide();
    }

}
}


WHP.pages.photo = {
    urlStr:"photo", //temp name for error page
    title:"",
    rndEnable:true,
    inited:false,
    mainObject:null,


    curPageId:null,
    curPageObject:null,


    mainImage:null,

    commentsCont : null,
    commentTemplateId : "template_photobig_comment",
    commentTemplate : null,
    commentMargin : 20,

    defaultStep : -28,


    photoGetTry : 0,
    photoGetMaxTries : 30,

    scrollToComments : false,

    postCommentNow : false,


    imagesList : null,



    init:function () {
        this.mainObject = id$('photo');

        this.commentsCont = $(this.mainObject).find( ".photobig_comments_container" );
        this.commentTemplate = document.getElementById(this.commentTemplateId);
        this.commentTemplate.removeAttribute('id');





        this.mainImage = $(this.mainObject).find(".photobig_photo_container");
        this.mainImage.parent = this;
        this.mainImage.shadow = $(this.mainObject).find(".photobig_shadow");

        this.mainImage.authorLCD = $(this.mainObject).find(".photobig_author_name");
        this.mainImage.scenarioLCD = $(this.mainObject).find(".photobig_theme_text");




        this.mainImage.rollover_plate = $(this.mainObject).find(".photobig_slider");
        var a = this.mainImage.rollover_plate;
        a.parentObject = this;
        a.parent = this.mainImage;
        a.show = bind(function() { this.showPlate(1) }, this.mainImage.rollover_plate);
        a.hide = bind(function() { this.showPlate(-1) }, this.mainImage.rollover_plate);
        a.showPlate = bind(this.showPlate, this.mainImage.rollover_plate);
        a.showControls = bind(this.showControls, this.mainImage.rollover_plate);
        this.mainImage.controls_container_block = $(this.mainObject).find(".controls_container_block");
        a.timer = new Timer(1000/35, 9);
        a.labels = $(this.mainObject).find(".labels");
        a.labels_timer = new Timer(1000/35, 3);
        a.labels_timer.onTimerEvent = bind(this.controlsHider,this.mainImage.rollover_plate);
        a.hC = 0;
        a.h0 = 0;
        a.h1 = 0;

        a.timer.onTimerEvent = bind(this.plateRolloverEvent,   this.mainImage.rollover_plate);
        a.cP = 0.0;
        a.p0 = 0.0;
        a.p1 = 0.0;
        a.backward_button = $(this.mainObject).find(".photobig_backward");
        a.forward_button = $(this.mainObject).find(".photobig_forward");
        a.move_label = $(this.mainObject).find(".photobig_label");
        a.removeIco = $(this.mainObject).find(".remove_image_ico");

        this.mainImage.likeShadow = $(this.mainObject).find(".photobig_like_shadow");


        this.imagesList = new whp_photolist_prototype();
        this.imagesList.rollover_plate =  a;
        this.mainImage.infoCont = $(this.mainObject).find(".photobig_text_container");
        this.imagesList.parent = this;
        this.imagesList.init();



        this.mainImage.imageHolder = $(this.mainObject).find(".photobig_image_container");
        this.mainImage.image = null;
        this.mainImage.image_cont = $(this.mainObject).find(".photobig_image_container_0");


        var startL = this.defaultStep;
        var shareElems = $(this.mainObject).find(".photobig_share_elem");
        shareElems.css({right: startL + 'px'});

        this.mainImage.shareCont = $(this.mainObject).find(".photobig_share_buttons_cont");

        this.mainImage.share_pt = $(shareElems[2]);
        this.mainImage.share_pt_ico = $(this.mainObject).find(".photobig_share_pt_0");
        this.setRolloverElem( this.mainImage.share_pt);

        this.mainImage.share_tw = $(shareElems[1]);
        this.mainImage.share_tw_ico = $(this.mainObject).find(".photobig_share_tw_0");
        this.setRolloverElem( this.mainImage.share_tw);

        this.mainImage.share_fb = $(shareElems[0]);
        this.mainImage.share_fb_ico = $(this.mainObject).find(".photobig_share_fb_0");
        this.setRolloverElem( this.mainImage.share_fb);




        a.mouseleave(bind(
            function(e){
               //cancelEvent(e);
            }, this.mainImage.rollover_plate));
        a.mouseenter(bind(
            function(e){
               cancelEvent(e);
            }, this.mainImage.rollover_plate));




        this.mainImage.controls_container_block.mouseleave(bind(
            function(e){
                if (this.parent.imagesList.active)
                    this.rollover_plate.showPlate(-1);

            }, this.mainImage));
        this.mainImage.controls_container_block.mouseenter(bind(
            function(e){
                if ((this.parent.imagesList.active) && (this.parent.imagesList.elements.length>1))
                    this.rollover_plate.showPlate(1);

            }, this.mainImage));



        this.mainImage.like_button = $(this.mainObject).find(".photobig_likes_0");
        this.mainImage.like_button.click( bind(this.clickLike, this));
        this.mainImage.like_button_label = $(this.mainObject).find(".photobig_likes_label");
        if (browser.firefox)
            this.mainImage.like_button_label.css({ left : 2+'px', top: 23+'px'});
        this.mainImage.setViewLikes = bind(this.setViewLikes, this);



        this.share.parent = this;
        this.comments.parent = this;
        this.likeLists.parent = this;
        this.removePhoto.parent = this;

        this.share.init();
        this.comments.init();
        this.likeLists.init();
        this.removePhoto.init();


        addIntelloLinks(this.mainImage);

        this.inited = true;
    },




    show:function (_q) {
        //_q - query string
        var q = _q;
        if (!q)
            q = "/";
        var params = q.split("/");
        var pageId = parseInt(params[0]);
        if (isNaN(pageId)) {
            log("WHP/pages/photo : parametres error");
            this.curPageId = null;
            WHP.controller.showErrorPage(1);
            return false;
        }


        //scrollTo comments
        this.scrollToComments = false;
        if (params.length > 1) {
            if (params[1].toLowerCase() == "comments")
                this.scrollToComments = true;
        }

        log("Scroll to comments = ["+this.scrollToComments+"]");


        this.curPageId = pageId;
        this.curPageObject = null;

        this.comments.clearComments();


        this.share.resetShare();


        this.imagesList.checkDisplay();

        this.removePhoto.checkButtonVisibility();
        this.getPicture();
        WHP.pages.photo.setHearts();

    },

    hide : function()
    {
        this.imagesList.clear();
    },

    createNewImage : function()
    {
        if (this.mainImage.image!=null)
        {
            this.mainImage.image.removeAttr("src");
            this.mainImage.image.remove();
        }

        this.mainImage.image = $(document.createElement("img"));
        setClass(this.mainImage.image, "photobig_image");
        this.mainImage.imageHolder.append(this.mainImage.image);
        this.mainImage.image.css({ visibility: 'hidden'});
    },

    getPicture:function (_NOTresetShare, _N) {
        if (!_NOTresetShare)
            this.mainImage.shareCont.css({display : 'none'});

        setClass(this.mainImage.image_cont, "photobig_image_container_0");
        //this.createNewImage();

        //clear
        this.mainImage.infoCont.css({ visibility : 'hidden'});
        this.mainImage.likeShadow.css({ visibility : 'hidden'});


        var Ncur = new Number(this.curPageId);
        if (typeof(Ncur) == 'undefined')
            Ncur = this.imagesList.position;

        this.removePhoto.checkButtonVisibility();

        $.ajax({
            url:WHP.netcalls.photoInfoCall,
            data : { r : Math.random(), photo : this.curPageId },
            timeout:WHP.netTimeOut,
            success:bind(function (e) { this.onData(e, Ncur) }, this),
            error:bind(this.onError, this)
        });
    },

    onError: function(response)
    {
        var status = response['status'];
        log("WHP/timeline_prot : error status = ["+status+"]");
        this.loading = false;
        if (status!=0)
        {
            this.photoGetTry++;
            if (this.photoGetTry >= this.photoGetMaxTries)
            {
                WHP.controller.showErrorPage(1);
                return false;
            }else{
                setTimeout(bind(this.getPicture,this), 1000*3.0);
            }
        }else{
            WHP.controller.showErrorPage();
        }
        //
    },

    setTitle : function()
    {
        this.title = this.getStoryName(this.curPageObject.photo.story)+" by "+this.curPageObject.photo.user.name;
        WHP.controller.setTitle();

    },

    onData:function (response)
    {
        if (!this.active)
            return false;

        this.photoGetTry = 0;
        WHP.controller.scrollToPos(0,0);
        var resp = getObjectJson(response);
        if (resp.error) {
            log("WHP/pages/photo : got picture error = [" + resp.error.code + "]");
            if (!WHP.errors.hasNetError(resp)) {
                WHP.controller.showErrorPage(1);
            }
            return false;
        }
       // this.curPageId = resp.photo.id;
        this.curPageObject = resp;

        this.setSizes();
        this.setImage(resp);
        this.mainImage.infoCont.css({ visibility : 'visible'});

        this.share.getNewShareButton();

        if (resp.photo.comments_count>0)
        {
            this.comments.getComments();
        }else{
            //no comments now!!
            log("NOCOMMETNS!");
            $(this.comments.newCommentContainer).css({ display : 'none' });
            this.comments.displayCommentBlock();
            this.comments.loadingComments = false;
            this.comments.lastParent = 0;
            this.comments.lastIndex = 0;
            this.comments.commentsTotal = 0;
            WHP.pages.photo.setHearts();
            this.comments.setWrappers();
            this.comments.checkScrollToComments();
            //this.comments.comments.commentsCurrent = this.comments.commentsCurrent + this.comments.getCurrentRootComments(resp.comments.list);
            this.comments.displayCommentBlock();
        }


        this.likeLists.getLikesLists();

        this.removePhoto.checkButtonVisibility();

        WHP.controller.showCanvas();

        if (resp.photo.comments_count==0)
        {
            this.comments.checkScrollToComments();
        }


        this.setTitle();
    },


    setSizes : function ()
    {
        var max_imageS = 810;
        var min_imageS = 512;

        var screenH = WHP.screenHl;

        var screen_step = 140;
        var round_step = 12;
        var bottom_step = 70;

        var imageS = screenH - screen_step - round_step - bottom_step;
        imageS = Math.min(max_imageS, Math.max(min_imageS, imageS));


        this.mainImage.shadow.css({width : imageS+2*round_step + 'px', display : ''});
        this.mainImage.image_cont.css({width : imageS + 'px', height : imageS + 'px'});
        this.mainImage.css({ width : imageS+2*round_step + 'px', height : imageS + round_step + bottom_step+'px', display : ''});
    },


    loadImage : function(_id)
    {
        if (_id != this.curPageId)
            return false;

        setClass(this.mainImage.image_cont, "photobig_image_container_1");
        this.mainImage.image.attr('src', this.curPageObject.photo['i1000x1000']);
        this.mainImage.image.css({ visibility: 'visible'});
        this.mainImage.likeShadow.css({ visibility: 'visible'});
    },



    controlsHider : function(e)
    {
        var A = e.currentCount/e.repeatCount;

        this.hC = (1-A)*this.h0 + A*this.h1;
        setAlpha(this.labels, this.hC);
    },

    showControls : function(_a)
    {
        if (_a)
        {
            this.h0 = this.hC;
            this.h1 = 1.0;
        }else{
            this.h0 = this.hC;
            this.h1 = 0.0;
        }
        this.labels_timer.reset();
        this.labels_timer.start();
    },

    showPlate : function (_a)
    {
        this.p0 = this.cP;
        if (_a>0)
        {
            this.p1 = 1.0;
        }else{
            this.showControls(false);
            this.p1 = 0.0;
        }

        this.timer.reset();
        this.timer.start();
    },

    plateRolloverEvent : function(e)
    {
        var A = e.currentCount/e.repeatCount;
        if (this.p0<this.p1)
        {
            var B = Math.pow( Math.sin(Math.PI*0.5*A), 0.18);
        }else{
            var B = Math.sin(Math.PI*0.5*A);
        }


        this.cP = (1-B)*this.p0 + B*this.p1;

        this.css({ height : 64*this.cP + 'px'});


        if (A>0.5)
        {
            if (this.p0<this.p1)
            {
                if (this.h0>=this.h1)
                {
                    this.showControls(true);
                }
            }
        }else{
            if (this.p0>this.p1)
            {
                if (this.h0<=this.h1)
                {
                    this.showControls(false);
                }
            }
        }
    },


    setRolloverElem : function(_elem)
    {
        if (_elem.rolloverElem)
            return false;

        _elem.rolloverElem = {
            timer : new Timer(1000/30, 6),
            cP : 0,
            p0 : 0,
            p1 : 0
        }
        _elem.disableBack = false;
        _elem.letsMove = bind(this.shareButtonMove, _elem);
        _elem.rolloverElem.timer.onTimerEvent = bind(this.shareButtonEventRollover, _elem);
        _elem.shareButtonMove = bind(this.shareButtonMove, _elem);
        _elem.disableAndMove = bind(this.disableAndMove, _elem);
        _elem.resetPos = bind(this.resetPos, _elem);

        _elem.mouseover(bind(function() { this.shareButtonMove(1); }, _elem));
        _elem.mouseout(bind(function() { this.shareButtonMove(-1); }, _elem));

    },

    resetPos : function()
    {
        this.rolloverElem.cP = 0;
        this.css({ right:  WHP.pages.photo.defaultStep + 'px'});
        this.disableBack = false;
    },

    disableAndMove : function()
    {
        this.shareButtonMove(1);
        this.disableBack = true;
    },

    shareButtonMove : function(_a)
    {
        if (this.disableBack && (this.rolloverElem.p1 == 1))
            return false;

        this.rolloverElem.p0 = this.rolloverElem.cP;
        if (_a>0)
        {
            this.rolloverElem.p1 = 1.0;
        }else{
            this.rolloverElem.p1 = 0.0;
        }
        this.rolloverElem.timer.reset();
        this.rolloverElem.timer.start();
    },

    shareButtonEventRollover : function(e)
    {
        var A = e.currentCount/e.repeatCount;
        var B = Math.sin(Math.PI*0.5*A);

        this.rolloverElem.cP = (1-B)*this.rolloverElem.p0 + B*this.rolloverElem.p1;
        this.css({ right: -this.rolloverElem.cP*18 + WHP.pages.photo.defaultStep + 'px'});
    },

    getStoryName : function (resp)
    {
        var storyName = "";
        if (resp)
        {
            if (resp.type=="STORY")
            {
                storyName = resp.name;
                this.mainImage.shareCont.css({display : 'block'});
            }else if (resp.type == "PRIVATE")
            {
                storyName = "Private photo";
                this.mainImage.shareCont.css({display : 'none'});
            }else if (resp.type == "TIMELINE")
            {
                storyName = "Snapshot";
                this.mainImage.shareCont.css({display : 'block'});
            }else if (resp.type == "DAILY")
            {
                storyName = resp.name;
                this.mainImage.shareCont.css({display : 'block'});
            }else if (resp.type == "USERSTORY")
            {
                storyName = resp.name;
                this.mainImage.shareCont.css({display : 'block'});
            }else if (resp.type == "UNSORTED")
            {
                storyName = resp.storyset.name;
                this.mainImage.shareCont.css({display : 'block'});
            }
        }else{
            storyName = "Other";
        }
        return storyName;
    },

    setImage : function(_resp)
    {
        log("SetImage");
        log(_resp);
        this.mainImage.authorLCD.text(_resp.photo.user.name);
        this.mainImage.authorLCD.attr("href", WHP.links.getUserProfileLink(_resp.photo.user.id));

        var timeS = this.mainImage.find(".photobig_timeshtamp");
        timeS.text(getTimeFormatedTl(_resp.photo.timestamp*1000));

        var caption = $(this.mainObject).find(".photobig_timeshtamp");
        var textCaption = $(this.mainObject).find(".timeline_caption_text_photo");
        if (_resp.photo.caption)
        {
            textCaption.text(_resp.photo.caption);
            textCaption.css({display :'block'});
        }else{
            textCaption.css({display :'none'});
        }

        var storyName = this.getStoryName(_resp.photo.story);
        if (_resp.photo.story.type == "PRIVATE")
        {
            this.mainImage.shareCont.css({display : 'none'});
        }else{
            this.mainImage.shareCont.css({display : 'block'});
        }

        this.mainImage.scenarioLCD.text(storyName);
        if (_resp.photo.story.type == "TIMELINE")
        {
            setClass(this.mainImage.scenarioLCD,"photobig_theme_text_na");
            this.mainImage.scenarioLCD.removeAttr("href");
        }else{
            setClass(this.mainImage.scenarioLCD,"photobig_theme_text");
            this.mainImage.scenarioLCD.attr("href", WHP.links.getScenarioLink(_resp.photo.story.id));
        }

        this.mainImage.setViewLikes();

        setClass(this.mainImage.image_cont, "photobig_image_container_0");

        this.createNewImage();
        var _id = new Number(this.curPageId);
        setImageOnload(this.mainImage.image, _resp.photo['i1000x1000'], null, bind(function() { this.loadImage(_id); }, this));
    },

    clickLike: function()
    {
        if (!WHP.auth.status)
        {
            WHP.loginMenus.showLoginMenu2();
            return false;
        }

        var wasVote = this.curPageObject.photo.wasvote;
        if (wasVote == 1)
            this.curPageObject.photo.like--;

        if (wasVote == 1)
        {
            wasVote = 0;
        }else{
            wasVote = 1;
            this.curPageObject.photo.like++;
        }
        this.curPageObject.photo.wasvote = wasVote;

        this.mainImage.setViewLikes();
        this.likeLists.setLikesMe();
        WHP.actions.likes.likePhoto(this.curPageObject.photo.id, this.curPageObject.photo.wasvote, "LIKE_PHOTO");
    },

    setViewLikes: function()
    {
        var wasvote = 0;
        if (typeof(this.curPageObject.photo.wasvote) != 'undefined')
            wasvote = this.curPageObject.photo.wasvote;

        setClass(this.mainImage.like_button, "photobig_likes_"+wasvote);
        this.mainImage.like_button_label.text(NformatMin(this.curPageObject.photo.like));
    },

    setHearts : function ()
    {
        var hasComments = this.comments.commentsList.length > 0;

        var hasLikes = (this.likeLists.likes.length > 0);
        if (WHP.pages.photo.curPageObject)
        if (WHP.pages.photo.curPageObject.photo)
             hasLikes =  hasLikes || (WHP.pages.photo.curPageObject.photo.wasvote!=0);

        var hasNewComment = (this.comments.newCommentContainer.style.display == 'block') && (this.comments.newCommentContainer.parentNode!=null);

        var commentsAre = hasNewComment || hasComments;
       // $(heartSplitters[0]).css( { display : 'block' });


        //new wrapper
        if (commentsAre)
            this.comments.addCommentCont.wrapper.css({ display : 'block'})
        else
            this.comments.addCommentCont.wrapper.css({ display : 'none'});

        //hearts
        var heartSplitters = $(WHP.pages.photo.mainObject).find( ".heart_split_container" );
        if (hasLikes)
        {
            $(heartSplitters[1]).css( { display : 'block' });
        }else{
            $(heartSplitters[1]).css( { display : 'none' });
        }
    },



    ///share
    share : {
        shareTW : null,

        shareFBsubscribeAssgned : false,
        shareTWsubscribeAssgned : false,


        sharedFB : false,
        sharedTW : false,
        sharedPT : false,
        parent : null,

        sharePageId : 0,

        pTwindow : null,
        pTurlChecker : new Timer(100,0),

        resetShare : function ()
        {
            setClass(this.parent.mainImage.share_tw_ico, "photobig_share_tw_0");
            setClass(this.parent.mainImage.share_fb_ico, "photobig_share_fb_0");
            this.sharePageId = WHP.pages.photo.curPageId;
            this.sharedFB = false;
            this.sharedTW = false;
            this.sharedPT = false;
            this.parent.mainImage.share_fb.resetPos();
            this.parent.mainImage.share_tw.resetPos();
        },

        onFBCallback : function (e)
        {
            if ((e) && (this.sharePageId == WHP.pages.photo.curPageId))
            {
                this.sharedFB = true;
                this.parent.mainImage.share_fb.disableAndMove();
                setClass(this.parent.mainImage.share_fb_ico, "photobig_share_fb_1");

                WHP.stats.trackShare("SHARE_FACEBOOK", WHP.pages.photo.curPageId);
            }
            return true;
        },

        onTWCallback : function (e)
        {
            if (this.sharePageId == WHP.pages.photo.curPageId)
            {
                this.sharedTW = true;
                this.parent.mainImage.share_tw.disableAndMove();
                setClass(this.parent.mainImage.share_tw_ico, "photobig_share_tw_1");

                WHP.stats.trackShare("SHARE_TWITTER", WHP.pages.photo.curPageId);
            }
            return true;
        },

        getStoryName : function (_resp)
        {
            var ret = _resp.story.name;
            if (_resp.story.type == "UNSORTED")
                ret = _resp.story.storyset.name;

            return ret;
        },

        getNewShareButton : function (e)
        {
            if (this.sharedTW)
                return false;

            var url = "http:" + WHP.links.getPhotoLink(this.parent.curPageObject.photo.id);

            var p = [];
            p.push("[pic] ");//0
            if (this.parent.curPageObject.photo.caption)
            {
                p.push(this.parent.curPageObject.photo.caption+" - "); //1
            }else{
                p.push("");
            }
            p.push(this.getStoryName(this.parent.curPageObject.photo)+" ");//2
            if (this.parent.curPageObject.photo.user.tw_name)
            {
                p.push("by @"+ this.parent.curPageObject.photo.user.tw_name+" ");       //3
            }else{
                p.push("by "+ this.parent.curPageObject.photo.user.name+" ");
            }
            p.push(url); //4   +13 symbols
            p.push(" %23whp");       //5



            log("share ->  ["+p.join("").length+"] ["+p.join("")+"]");

            if (p.join("")>140)
            {
                p.splice(5,1);
                log("1* ["+p.join("").length+"] ["+p.join("")+"]");
                //whp
                if (p.join("")>140)
                {
                    //pic
                    p.splice(0,1);
                    log("1* ["+p.join("").length+"] ["+p.join("")+"]");
                    if (p.join("")>140)
                    {
                        //storyname
                        p.splice(1,1);
                        p[0] = p[0].substring(0, p[0].lastIndexOf(" - "));
                        log("1* ["+p.join("").length+"] ["+p.join("")+"]");
                        if (p.join("")>140)
                        {
                            //user
                            p.splice(1,1);
                            log("1* ["+p.join("").length+"] ["+p.join("")+"]");

                            if (p.join("")>140)
                            {
                                p[0] = p[0].substring(0, 140-p[1].length-4)+"... ";
                            }
                        }
                    }
                }
            }

            this.shareTW.href = "http://twitter.com/intent/tweet?text="+p.join("");
        },

        clickTW : function(e)
        {
            this.setShareEvents();


        },

        clickFB : function(e)
        {
            log("CLICK FB!");
            if (this.sharedFB)
                return false;

            var pic = this.parent.curPageObject.photo['i106x106'];
            var url = "http:"+WHP.links.getPhotoLink(this.parent.curPageObject.photo.id);
            var storyName = this.parent.getStoryName(this.parent.curPageObject.photo.story);

            /*
            if (_resp.photo.story.type == "TIMELINE")
            {
                storyName = "Other";
            }else{
                storyName = _resp.photo.story.name;
            }*/

            //https://www.facebook.com/dialog/feed?access_token=AAAC7PHlqPP0BABPslrmR2Hh56kUPYgaxBmcqXZBwzXI1oMRRdFmIp8tcMcVnMQhzHBUe8YsZAbM3OZC4fh84luER5KkZCZBQENt3ZAbfuOowZDZD&actions=%5B%7B%22name%22%3A%22Get%20WeHeartPics%22%2C%22link%22%3A%22http%3A%2F%2Fitunes.apple.com%2Fapp%2Fweheartpics%2Fid488515478%3Fmt%3D8%22%7D%5D&api_key=205868409437437&app_id=205868409437437&caption=WeHeartPics.com&description=&display=popup&link=http%3A%2F%2F%2F%2Fwhptest.weheartpics.com%2Fphoto%2F30173%2F&locale=en_US&name=Snapshot&next=http%3A%2F%2Fstatic.ak.facebook.com%2Fconnect%2Fxd_arbiter.php%3Fversion%3D6%23cb%3Df2484606ac%26origin%3Dhttp%253A%252F%252Fwhptest.weheartpics.com%252Ff57b9c1ac%26domain%3Dwhptest.weheartpics.com%26relation%3Dopener%26frame%3Df3e0ce3aac%26result%3D%2522xxRESULTTOKENxx%2522&picture=http%3A%2F%2Fwhpt1.s3-website-us-east-1.amazonaws.com%2Fphoto%2F106x106%2F30173.jpg&sdk=joey

            FB.ui({
                method: "feed",
                display: "popup",
                link: url,
                name: storyName,
                caption: "WeHeartPics.com",
                description : "",
                actions: [
                    { name: 'Get WeHeartPics', link: WHP.apple_store_link }
                ],
                picture: pic
            }, bind(this.onFBCallback, this));
        },


        clickPT : function(e)
        {
            if (this.sharedPT)
                return false;

            // Caption - 2nd level name [#optional2ndLevel #2ndLevelName(берутся из одного поля) #1LevelName #GetWeheartPics


            this.pTwindow = openWindow2("Create pin", 600, 420);
            this.pTurlChecker.start();

            var img = this.parent.curPageObject.photo['i1000x1000'];
            var url = "http://"+WHP.links.getPhotoLink(this.parent.curPageObject.photo.id);
            var title = this.parent.getStoryName(this.parent.curPageObject.photo.story);


            var p = [];
            if (this.parent.curPageObject.photo.caption)
            {
                p.push(this.parent.curPageObject.photo.caption+" - "); //0
            }else{
                p.push("");
            }


            p.push(this.getStoryName(this.parent.curPageObject.photo)+" ");//1


            if (WHP.auth.status)
            if (this.parent.curPageObject.photo.user.id != WHP.auth.status.id)
            {
                p.push("by "+ this.parent.curPageObject.photo.user.name+" ");
            }


            if (this.parent.curPageObject.photo.story.storyset)
            {
                p.push(this.parent.curPageObject.photo.story.storyset.pinterest_hashtags+" ");
                if (this.parent.curPageObject.photo.story.storyset.storycat)
                    p.push(this.parent.curPageObject.photo.story.storyset.storycat.pinterest_hashtags);
            }else{
                p.push(this.parent.curPageObject.photo.story.pinterest_hashtags+" ");
            }
            p.push(" #GetWeHeartPics");       //5
            var desc = p.join("");
            while (desc.indexOf("#")>-1)
                desc = desc.replace("#","%23");


            var link = "http://pinterest.com/pin/create/bookmarklet/?media="+img+"&url="+url+"&title="+title+"&is_video=false&description="+desc;
            this.pTwindow.location = link;

            WHP.stats.trackShare("SHARE_PINTEREST", WHP.pages.photo.curPageId);
            //http://pinterest.com/pin/create/bookmarklet/

        },

        onPTCallback : function (e)
        {
            if (this.sharePageId == WHP.pages.photo.curPageId)
            {
                this.sharedPT = true;
                this.parent.mainImage.share_tw.disableAndMove();
                setClass(this.parent.mainImage.share_tw_ico, "photobig_share_pt_1");
            }
            return true;
        },



        setShareEvents : function ()
        {
            if ((typeof(twttr) != 'undefined') && (!this.shareTWsubscribeAssgned))
            {
                twttr.events.bind('tweet', bind(this.onTWCallback,this));
                this.shareTWsubscribeAssgned = true;
            }
            if ((typeof(FB) != 'undefined') && (!this.shareFBsubscribeAssgned))
            {
                //FB.Event.subscribe('edge.create', bind(this.onFBCallback,this));
                this.shareFBsubscribeAssgned = true;
            }
        },

        ptChecker: function(e)
        {
            if (this.pTwindow)
            {
               // log("url = ["+this.pTwindow.location+"]");
            }else{
                e.target.reset();
            }
        },

        init : function()
        {
            this.shareTW = WHP.pages.photo.mainImage.share_tw_ico.get()[0];
            this.shareTW.hasIntelloLinker = true;
            this.pTurlChecker.onTimerEvent = bind(this.ptChecker, this);
            this.setShareEvents();
        }
    },



    removePhoto : {
        icon : null,
        rWind : null,

        timer : new Timer(1000/30, 4),
        windA : {
            cP : 0,
            p0 : 0,
            p1 : 0,
            visible : false
        },

        parent : null,

        init : function()
        {
            this.icon = this.parent.mainImage.rollover_plate.removeIco;
            this.icon.click( bind(this.clickRemoveButton, this));


            this.rWind = $(this.parent.mainObject).find(".remove_window");
            setAlpha(this.rWind, 0);

            var buttons = this.rWind.find(".unfollow_button");

            this.rWind.yesButton = $(buttons[0]);
            this.rWind.yesButton.click(bind(this.yesClick, this));
            this.rWind.noButton = $(buttons[1]);
            this.rWind.noButton.click(bind(this.noClick, this));


            this.timer.onTimerEvent = bind(this.showHideTimer, this);
            this.checkButtonVisibility();
        },

        checkButtonVisibility : function()
        {
            var visible = this.chSmall();

            if (visible)
            {
                this.icon.css({display : 'block'});
            }else{
                this.icon.css({display : 'none'});
            }
        },

        chSmall : function ()
        {
            //return false;

            if (!WHP.auth.status)
                return false;

            if (!this.parent.curPageObject)
                return false;

            if (WHP.auth.status.id != this.parent.curPageObject.photo.user.id)
                return false;


            return true;
        },

        yesClick : function(e)
        {
            this.removePhoto();
            this.hide();

            return cancelEvent(e);
        },

        noClick : function(e)
        {
            this.hide();

            return cancelEvent(e);
        },

        showHideTimer : function(e)
        {
            var A = e.currentCount/e.repeatCount;


            this.windA.cP = (1-A)*this.windA.p0 + A*this.windA.p1;

            setAlpha(this.rWind, this.windA.cP);

            if (A == 1)
            {
                if (this.windA.cP == 0)
                    this.rWind.css({ display : 'none' });
            }
        },

        show : function()
        {
            if (!this.rWind)
                return false;

            if ( this.rWind.css('display') == 'none')
                this.rWind.css({ display : 'block' });

            this.windA.visible = true;

            this.windA.p0 = this.windA.cP;
            this.windA.p1 = 1.0;
            this.timer.reset();
            this.timer.start();
        },

        hide : function()
        {
            this.windA.visible = false;

            if (!this.rWind)
                return false;

            this.windA.p0 = this.windA.cP;
            this.windA.p1 = 0.0;
            this.timer.reset();
            this.timer.start();
        },

        clickRemoveButton : function(e)
        {
            if (!this.chSmall())
                return false;

            //showWind
            if (this.windA.visible)
                this.hide()
            else
                this.show();
        },

        removePhoto : function()
        {
            if (!this.chSmall())
                return false;



            var curPageId = this.parent.curPageObject.photo.id;

            //this.onData(null, curPageId);
            //return false;

            $.ajax({
                url:WHP.netcalls.deletePhotoCall,
                data : { r : Math.random(), photo :  curPageId },
                timeout:WHP.netTimeOut,
                success:bind(function (e) { this.onData(e, curPageId); }, this),
                error:bind(this.onError, this)
            });
        },

        moveto : function()
        {
            WHP.controller.navigateTo(WHP.links.getUserProfileLink(WHP.auth.status.id));
            return false;
        },

        removePhotoList : function()
        {

            var lastPage = this.getPrevMainPage();
            var lastPopular = (lastPage.indexOf("popular") == 0);
            var il = this.parent.imagesList;

            log("----------------------");
            log("Get last not photo = ["+lastPage+"]");

            if (lastPopular)
            {
                log("1) POPULAR.LIST nextPhoto >");
                il.elements.splice(il.position,1);
                il.position = Math.min(il.elements.length-1,il.position);
                il.setPosition(0);

                return false;
            }

            if ((!il.userUrl) || (il.userUrl && (il.total<il.limit)))
            {
                log("PHOTO il.len = ["+il.elements.length+"]");
                log("2) NET.LIST+limited || NET.stack");
                if (il.elements.length <= 1)
                {
                    //last photo in stack was removed
                    this.stepBack();
                    //check
                }else{
                    //ok
                    il.elements.splice(il.position,1);
                    il.total--;
                    il.position = Math.min(il.elements.length-1,il.position);
                    //refresh photo
                    il.setPosition(0);
                }
                return false;
            }

            if (il.userUrl)
            {
                log("NET.LIST");

                il.elements.splice(il.position,1);
                il.total--;
                il.position = Math.min(il.elements.length-1,il.position);

                il.setPosition(0);
                return false;
            }

            log("OTHER");
            this.stepBack();

            //photo from timeline
            //unlimited net.stack



            log("----------------------");


        },

        stepBack : function()
        {
            WHP.controller.afterRemoveBack = true;
            history.back();
        },

        getPrevMainPage : function()
        {
            var ret = null;
            var hist = WHP.controller.history;

            for (var i = hist.length-1; i>=0; i--)
            {
                if (hist[i].url.indexOf("photo/")==-1)
                {
                    ret = hist[i].url;
                    break;
                }
            }

            return ret;
        },

        moveBack : function()
        {
            var hist = WHP.controller.history;


            var retUrl = "";
            for (var i = hist.length-1; i>=0; i--)
            {
                if (hist[i].url.indexOf("photo/")==-1)
                {
                    retUrl = hist[i].url;
                    break;
                }
            }

            if (retUrl!="")
            {
                WHP.controller.navigateTo(retUrl);
            }else{
                this.moveto();
            }
        },

        onData : function (response, removedId)
        {
            if (response)
            {
                var resp = getObjectJson(response);
                if (resp.error)
                {
                    if (!WHP.errors.hasNetError(resp))
                    {
                        WHP.controller.showErrorPage(1);
                    }
                    return false;
                }
            }

            WHP.controller.removedList.push(removedId);


            var hist = WHP.controller.history;

            //back to the main page if user opened only this photo
            if (hist.length == 0)
            {
                WHP.controller.navigateTo("timeline");
                return false;
            }

            this.removePhotoList();
        },


        onError : function (response)
        {
            WHP.controller.showErrorPage(1);
        }
    },




    comments : {
        commentsList : [],
        commentsTotal : 0,
        commentsCurrent : 0,
        charLimit : 1000,

        newCommentName : null,
        newCommentContainerId : "template_photobig_newcomment",
        newCommentContainer : null,
        newCommentTextInput : null,
        newCommentMessageCont : null,
        newCommentMessageWrapper : null,
        newCommentButtonOk : null,
        newCommentReply : null,
        newCommentTextInputC : null,


        loadingComments : false,

        loadingBar : null,


        addCommentCont : null,

        lastParent : 0,
        lastIndex : 0,

        inited : false,

        parent : null,


        getComments: function ()
        {
            this.loadingComments = true;

            $(this.newCommentContainer).css({ display : 'none' });

            var curId = new Number(this.parent.curPageId);
            $(WHP.pages.photo.commentsCont).append(this.loadingBar);
            WHP.actions.comments.getComments(WHP.pages.photo.curPageId, bind(function (e) { if (curId == this.parent.curPageId) this.onData(e);}, this), bind(this.onErr, this));
            this.displayCommentBlock();
        },

        onErr : function(response)
        {
            this.loadingComments = false;
        },

        onData : function (response, status, xhr)
        {
            this.loadingComments = false;
            this.lastParent = 0;
            this.lastIndex = 0;
            var resp = getObjectJson(response);
            if (resp.error)
            {
                log("WHP/pages/photo/comments : Err = ["+resp.error.code+"]");
                if (!WHP.errors.hasNetError(resp))
                {
                    //WHP.controller.showErrorPage();
                }
                return false;
            }

            this.loadingBar.detach();
            //positon delta
            var level1 = WHP.pages.photo.commentMargin;
            this.commentsTotal = resp.comments.total;

            //set hearts

            WHP.pages.photo.setHearts();


            var lastPr = 0;
            for (var i=0; i<resp.comments.list.length; i++)
            {
                var element_div = this.newComment(resp.comments.list[i]);
                if (element_div.level == 0)
                    this.lastParent = new Number(i);
                element_div.parentN = this.lastParent;
                element_div.index = parseInt(new Number(i));

                $(WHP.pages.photo.commentsCont).append(element_div);
                this.commentsList.push(element_div);
            }

            WHP.pages.photo.setHearts();
            this.setWrappers();
            this.commentsCurrent = this.commentsCurrent + this.getCurrentRootComments(resp.comments.list);



            this.checkScrollToComments();

            this.displayCommentBlock();

            if (this.commentsCurrent != this.commentsTotal)
            {
                //ther is another block of comments
            }else{
                //no more comments
            }
           // WHP.resetH();
        },


        checkScrollToComments : function()
        {
            log("CHECK");
            if (WHP.controller.visible)
            {
                log("VISIBLE");
                if (WHP.pages.photo.scrollToComments)
                {
                    log("SCROLL");
                    var pos = $(this.addCommentCont).offset().top-86;
                    WHP.smoothScrollTo(0, pos);
                }
                WHP.pages.photo.scrollToComments = false;
            }

        },

        newComment : function (_comObj)
        {
            var element_div = $(WHP.pages.photo.commentTemplate).clone();

            element_div.author = $(element_div).find( ".comment_username" );
            element_div.author.attr("href", WHP.links.getUserProfileLink(_comObj.user.id));
            element_div.author.text(_comObj.user.name);

            element_div.timeShtamp = $(element_div).find( ".comment_info" );
            element_div.timeShtamp.text(getTimeFormated(parseInt(_comObj.date)*1000));

            element_div.commentBody = $(element_div).find( ".comment_body" );
            var mes = _comObj.text;
            while (mes.indexOf("<")>0)
                mes = mes.replace("<", "&lt;");
            while (mes.indexOf(">")>0)
                mes = mes.replace(">", "&gt;")



            element_div.commentBody.html(mes);
            element_div.commentBody.linkify();

            element_div.marginer = $(element_div).find( ".comments_container_marginer" );
            element_div.wrapper = $(element_div).find( ".line_wrapper" );

            element_div.comment_id = _comObj.id;
            element_div.level = _comObj.level;

            if (element_div.level != 0)
            {
                element_div.marginer.css( { 'margin-left' : WHP.pages.photo.commentMargin} );
            }




            addIntelloLinks(element_div);
            return element_div;
        },

        getCurrentRootComments : function (_arr)
        {
            var ret = 0;
            if (!_arr)
                return -1;

            for (var i=0; i<_arr.length; i++)
            {
                if (_arr[i].level == 0)
                    ret++;
            }
            return ret;
        },
        clearComments : function ()
        {
            this.commentsTotal = 0;
            this.commentsCurrent = 0;
            while(this.commentsList.length>0)
            {
                var a = $(this.commentsList.pop());
                a.remove();
            }
            this.displayCommentBlock();
        },

        startPostComment : function (e)
        {
            if (!WHP.auth.status)
            {
                WHP.loginMenus.showLoginMenu2();
                return false;
            }


            this.beginPost(null);
        },
        onCommentsSent : function (response)
        {
            var resp = getObjectJson(response);
            if (resp.error)
            {
                log("WHP/pages/photo/comments : get post comment error = ["+resp.error.code+"]");
                if (!WHP.errors.hasNetError(resp))
                {
                    //WHP.controller.showErrorPage();
                }
                return false;
            }
            log("WHP/pages/photo/comments : get comment ["+response+"]");
        },


        focusInput : function ()
        {
            this.newCommentTextInput.focus();
        },

        beginPost : function (_reply)
        {
            if (!WHP.auth.status)
            {
                WHP.loginMenus.showLoginMenu2();
                return false;
            }

            var level1 = WHP.pages.photo.commentMargin;
            var lastIndex = this.commentsList.length-1;
            if (_reply)
            {
                //get lastObject of comments block
                this.newCommentReply = _reply.comment_id;
                lastIndex = _reply.index.valueOf();

                var lI = lastIndex;
                if (_reply.level==0)
                    for (var i=lI+1; i < this.commentsList.length; i++)
                    {
                        if (this.commentsList[i].level == 1)
                            lI = i
                        else
                            break;
                    }
                lastIndex = lI;

                this.newCommentMessageMarginer.css({ 'margin-left' : level1 });
                this.setWrappers(	lastIndex, 1);
            }else{
                //root
                this.newCommentReply = null;
                this.newCommentMessageMarginer.css({ 'margin-left' : 0 });
                this.setWrappers(	lastIndex, 0);
            }
            $(this.newCommentContainer).css({ display : 'block' });
            this.newCommentTextInput.value = "";

            //this.newCommentUserName.innerHTML = WHP.auth.userObject.name;
            this.commentOnKey();

            this.lastIndex = lastIndex;

            if (this.lastIndex>=0)
                $(this.newCommentContainer).insertAfter(this.commentsList[lastIndex])
            else
                $(WHP.pages.photo.commentsCont).append(this.newCommentContainer);

            WHP.pages.photo.setHearts();


            var s1 = $(document).scrollTop();
            var s2 = s1+WHP.screenHl;

            var p1 = $(this.newCommentContainer).offset().top;
            var p2 = p1+$(this.newCommentContainer).height();

            if ((p1<s1) || (p1>s2) || (p2<s1) || (p2>s2))
            {
                newP = Math.max(0, p1-WHP.screenHl*0.5);
                WHP.smoothScrollTo( 0, newP, bind(this.focusInput, this));
            }else{
                this.newCommentTextInput.focus();
            }

            this.newCommentName.html(WHP.auth.userObject.name+" :");
            this.newCommentName.attr('href', WHP.links.getUserProfileLink(WHP.auth.status.id));

            addIntelloLinks(this.newCommentContainer);

            //this.newCommentTextInput.focus();
        },

        commentOnKey : function (e)
        {
            var minH = 70;
            var charLimit = WHP.pages.photo.comments.charLimit;
            var okButton = WHP.pages.photo.comments.newCommentButtonOk;
            var input = WHP.pages.photo.comments.newCommentTextInput;
            var inputC = WHP.pages.photo.comments.newCommentTextInputC;
            var messageBox = WHP.pages.photo.comments.newCommentMessageCont;
            var lengthI = input.value.length;
            var delt = charLimit - lengthI;

            //setHeight
            input.style.height = "auto";
            var h = input.scrollHeight;
            if (h<minH)
                h = minH;
            h = h + 20;
            input.style.height = h+'px';
            inputC.style.height = h+'px';


            if (delt<100)
                messageBox.style.visibility = "visible";
            else
                messageBox.style.visibility = "hidden";



            if ((lengthI>0) && ((lengthI <= charLimit)) && checkInputEmpty(input.value))
            {
                setClass(okButton, "fast_comment_ok");
                if (delt<100)
                    messageBox.style.visibility = "visible"
                else
                    messageBox.style.visibility = "hidden";
                if (delt>30)
                {
                    setClass(messageBox, "fast_comment_message_holder");
                }else{
                    setClass(messageBox, "fast_comment_message_holder_warning");
                }
            }else{
                setClass(okButton, "fast_comment_ok_disabled");
            }


            //formating message
            var mesPre = " characters left";
            if (delt==1)
            {
                mesPre = " character left";
            }
            messageBox.innerHTML = delt+mesPre;
        },

        postComment : function (e)
        {
            log("1post comment");
            if (this.postCommentNow)
                return false;

            log("2post comment");
            if (!WHP.auth.status)
            {
                WHP.loginMenus.showLoginMenu2();
                return false;
            }


            log("3post comment");
            this.postCommentNow = true;
            var input = WHP.pages.photo.comments.newCommentTextInput;
            var charLimit = WHP.pages.photo.comments.charLimit;
            var photo_id = WHP.pages.photo.curPageId;
            var reply = WHP.pages.photo.comments.newCommentReply;

            if ((input.value.length <= charLimit) && (input.value.length>0))
            {
                log("4post comment");
                var comBody = messageCheckSPaces(input.value);
                WHP.actions.comments.postComment( photo_id , reply, comBody, bind(this.postCommentCallback, WHP.pages.photo.comments), bind(this.errcbComment, this));
            }
        },

        errcbComment : function(response)
        {
            this.postCommentNow = false;
        },

        postCommentCallback : function (response)
        {
            this.postCommentNow = false;
            var resp = getObjectJson(response);
            if (resp.error)
            {
                log("WHP/pages/photo/likeLists : get lists error = ["+resp.error.code+"]");
                if (!WHP.errors.hasNetError(resp))
                {
                    //WHP.controller.showErrorPage();
                }
                return false;
            }

            var element_div = this.newComment(resp.comment);

            this.commentsList.splice(this.lastIndex+1,0,element_div);
            if (resp.comment.level == 0)
                this.lastParent = new Number(this.commentsList.length-1);
            //set indexes
            for (var i = 0; i<this.commentsList.length; i++)
                this.commentsList[i].index = parseInt(new Number(i));
            element_div.parentN = this.lastParent;

            this.setWrappers();
            $(element_div).insertAfter(this.newCommentContainer);
            $(this.newCommentContainer).remove();
            WHP.pages.photo.setHearts();
            this.displayCommentBlock();
        },

        cancelComment : function (e)
        {
            var comments = WHP.pages.photo.comments;
            comments.setWrappers();
            $(comments.newCommentContainer).remove();
            WHP.pages.photo.setHearts();
        },

        setWrappers : function (_lastComment, _curLevel)
        {
            var level1 = WHP.pages.photo.commentMargin;
            for (var i=0; i<this.commentsList.length; i++)
            {
                var element_div = this.commentsList[i];
                element_div.wrapper.css({ visibility : 'visible' });
                if (element_div.level == 1)
                {
                    element_div.wrapper.css({ 'margin-left' : level1 });
                    if (i < this.commentsList.length-1)
                        if (this.commentsList[i+1].level == 0)
                            element_div.wrapper.css({ 'margin-left' : 0 });
                }else{
                    element_div.wrapper.css({ 'margin-left' : 0 });
                }
            }

            if (this.commentsList.length>0)
                this.commentsList[this.commentsList.length-1].wrapper.css({ visibility : 'hidden' });

            if ( typeof(_lastComment) != 'undefined' )
            {
                if (_lastComment>0)
                {
                    var lastCom = this.commentsList[_lastComment];
                    lastCom.wrapper.css({ visibility : 'visible' });
                    if (lastCom.level == 0)
                    {
                        lastCom.wrapper.css({ 'margin-left' : 0 });
                    }else{
                        lastCom.wrapper.css({ 'margin-left' : level1 });
                    }
                }

                if (_lastComment == this.commentsList.length-1)
                {
                    if (_lastComment>-1)
                    {
                        var lastCom = this.commentsList[_lastComment];
                        lastCom.wrapper.css({ visibility : 'visible' });
                    }
                    this.newCommentMessageWrapper.css({ visibility : 'hidden' });
                }else{
                    this.newCommentMessageWrapper.css({ visibility : 'visible' });
                    if (_curLevel == 0)
                    {
                        this.newCommentMessageMarginer.css({ 'margin-left' : 0 });
                    }else{
                        this.newCommentMessageMarginer.css({ 'margin-left' : level1 });
                    }
                }
            }
        },

        displayCommentBlock : function()
        {
            if ( this.loadingComments )
            {
                this.addCommentCont.commentsCount.text("");
                this.addCommentCont.addNew.text("");
                return true;
            }

            if (this.commentsList.length>0)
            {
                if (this.commentsList.length==1)
                    this.addCommentCont.commentsCount.text("1 comment ")
                else
                    this.addCommentCont.commentsCount.text(this.commentsList.length+" comments ");

                this.addCommentCont.addNew.text("Add new");
            }else{
                this.addCommentCont.commentsCount.text("");
                this.addCommentCont.addNew.text("Add new comment");
            }
        },

        init : function ()
        {
            this.newCommentContainer = document.getElementById(this.newCommentContainerId);
            this.newCommentTextInput = $(this.newCommentContainer).find( ".photo_newcomment_commentinput" ).get()[0];
            this.newCommentTextInputC = $(this.newCommentContainer).find( ".comment_body" ).get()[0];
            this.newCommentTextInput.maxLength = this.charLimit;

            this.newCommentName = $(this.newCommentContainer).find( ".comment_username" );

            this.newCommentMessageCont = $(this.newCommentContainer).find( ".comment_info" ).get()[0];
            this.newCommentButtonOk = $(this.newCommentContainer).find( ".fast_comment_ok" ).get()[0];
            this.newCommentMessageMarginer = $(this.newCommentContainer).find( ".comments_container_marginer" );
            this.newCommentMessageWrapper = $(this.newCommentContainer).find( ".line_wrapper" );

            this.addCommentCont = $(this.parent.mainObject).find(".photobig_addcomment_container");
            this.addCommentCont.commentsCount = $(this.addCommentCont).find(".photobig_comments_count");
            this.addCommentCont.addNew = $(this.addCommentCont).find(".photobig_addnew");
            this.addCommentCont.addNew.click(bind(this.startPostComment,this));
            this.addCommentCont.wrapper = $(this.addCommentCont).find(".line_wrapper");

            this.loadingBar = $("#notifications_loading_tab").clone().removeAttr('id');
            this.loadingBar.css({ display : 'block', margin : 'auto', width: 50+'px'});



            this.inited = true;
        }
    },

    likeLists : {
        likes : [],
        likesReceived : false,

        listContainer : null,

        likesHeader : null,
        dislikesHeader : null,

        likesBody : null,
        dislikesBody : null,
        likesBodyC : null,
        dislikesBodyC : null,

        meLike : null,
        meDislike : null,
        parent : null,

        getLikesLists : function()
        {
            WHP.pages.photo.likeLists.clearCanvas();
            WHP.pages.photo.likeLists.listContainer.css({ display : 'none' });


            var curId = new Number(this.parent.curPageId);
            WHP.actions.likes.getLikeList(    WHP.pages.photo.curPageId, bind( function(e) {  if (curId == this.parent.curPageId) WHP.pages.photo.likeLists.dataCallBack(e); }, WHP.pages.photo.likeLists));
            //WHP.actions.likes.getDislikeList( WHP.pages.photo.curPageId, bind( this.dataCallBack, this));
        },

        dataCallBack : function(response)
        {
            var resp = getObjectJson(response);
            if (resp.error)
            {
                log("WHP/pages/photo/likeLists : get lists error = ["+resp.error.code+"]");
                if (!WHP.errors.hasNetError(resp))
                {
                    //WHP.controller.showErrorPage();
                }
                return false;
            }

            //likes
            for (var i=0; i<resp.friend_likes.length; i++)
            {
                if ((!WHP.auth.status) || (parseInt(resp.friend_likes[i].id) != WHP.auth.status.id))
                    this.likes.push( resp.friend_likes[i] );
            }
            for (var i=0; i<resp.likes.length; i++)
            {
                this.likes.push( resp.likes[i] );
            }

            this.likesReceived = true;


            var str = "";
            for (var i=0; i<this.likes.length; i++)
            {
                if (i!=this.likes.length-1)
                    str = str + "<a href='" + WHP.links.getUserProfileLink(this.likes[i].id) + "' class='photobig_like_username'>"+this.likes[i].name+"</a>, "
                else
                    str = str + "<a href='" + WHP.links.getUserProfileLink(this.likes[i].id) + "' class='photobig_like_username'>"+this.likes[i].name+"</a>";
            }
            this.likesBody.innerHTML = str;





            WHP.pages.photo.likeLists.setLikesMe();
            WHP.pages.photo.setHearts();

            addIntelloLinks(this.likesBody);

            //WHP.resetH();
        },

        clearCanvas : function()
        {
            //clear
            while(this.likes.length>0)
            {
                var a = this.likes.pop();
                $(a).remove();
            }

            this.likesBody.innerHTML = "";
            this.likesReceived = false;
        },

        clearLikesMe : function()
        {
            WHP.pages.photo.likeLists.meDislike.innerHTML = "";
            WHP.pages.photo.likeLists.meLike.innerHTML = "";
        },

        setLikesMe : function()
        {
            if (WHP.pages.photo.curPageObject == null)
                return false;

            if (WHP.pages.photo.curPageObject.photo.wasvote > 0)
            {
                WHP.pages.photo.likeLists.meDislike.innerHTML = "";
                if (WHP.pages.photo.likeLists.likes.length >0)
                    WHP.pages.photo.likeLists.meLike.innerHTML = "<a href='" + WHP.links.getUserProfileLink(WHP.auth.status.id) + "' class='photobig_like_username'>"+WHP.auth.userObject.name+"</a>"+", "
                else
                    WHP.pages.photo.likeLists.meLike.innerHTML = "<a href='" + WHP.links.getUserProfileLink(WHP.auth.status.id) + "' class='photobig_like_username'>"+WHP.auth.userObject.name+"</a>";

                addIntelloLinks(WHP.pages.photo.likeLists.meLike);
            }else{
                this.clearLikesMe();
            }

            //check likes displaying

            if ((this.likes.length>0) || (WHP.pages.photo.curPageObject.photo.wasvote!=0))
            {
                this.listContainer.css({ display : 'block' });
            }else{
                this.listContainer.css({ display : 'none' });
            }

            WHP.pages.photo.setHearts();
            WHP.pages.photo.likeLists.checkLikesStatus();
        },
        checkLikesStatus : function()
        {
            var sourceLikes = WHP.pages.photo.curPageObject.photo.like;

            if (sourceLikes == 1)
                WHP.pages.photo.likeLists.likesHeader.innerHTML = sourceLikes + "&nbsp;Like"
            else
                WHP.pages.photo.likeLists.likesHeader.innerHTML = sourceLikes + "&nbsp;Likes";

        },

        init : function()
        {
            this.listContainer = $(WHP.pages.photo.mainObject).find( ".photobig_likesbox_holder");
            var obj = $(WHP.pages.photo.mainObject).find( ".photobig_like_header" );
            this.likesHeader = obj[0];
            this.dislikesHeader = obj[1];

            var obj = $(WHP.pages.photo.mainObject).find( ".photobig_like_body" );
            this.likesBodyC = obj[0];
            this.dislikesBodyC = obj[1];

            var obj = $(WHP.pages.photo.mainObject).find( ".photobig_like_body_cont" );
            this.likesBody = obj[0];
            this.dislikesBody = obj[1];


            this.meLike = $(this.likesBodyC).find( ".photobig_like_username" ).get()[0];
            this.meDislike = $(this.dislikesBodyC).find( ".photobig_like_username" ).get()[0];
        }
    }
}


API_Auth_Failed = 'API_AuthFailed';


WHP.errors = {
    hasNetError : function(_resp)
    {
        if (_resp.error.code == API_Auth_Failed)
        {
            log("WHP/errors : got error = ["+API_Auth_Failed+"]");
            WHP.auth.authError();
            return true;
        }
        return false;
    }
};
WHP.stats = {
    inited : false,
    trackPermission : false,

    commentsCount : 0,
    likesCount : 0,

    init : function()
    {
        this.trackPermission = (WHP.domain.indexOf("test") == -1);
    },

    trackPageChange : function(_url)
    {
        if (!this.trackPermission)
            return false;

        if (!WHP.controller.curPage)
            return true;

        if ((WHP.controller.curPage.urlStr == "profile") && (WHP.auth.status))
        {
            //for profile tracking
            str = "/profile/"+WHP.pages.profile.states[WHP.pages.profile.curState].urlPrefix;
        }else{
            var str = new String(_url);
            if (str.charAt(0)!="/")
                str = "/"+str;
        }





        log("WHP/stats : Track page = ["+str+"]");

        _gaq.push(['_trackPageview', str]);

    },

    trackLike : function(_label)
    {
        if (!this.trackPermission)
            return false;
        log("WHP/stats : Track like");
        _gaq.push(['_trackEvent', 'Photo', 'like', _label]);

    },

    getCommentsCount : function()
    {
        var counter = parseInt(getCookie("whp_comc"));
        if (isNaN(counter))
        {
            counter = 0;
        }
        return counter;
    },

    getLikesCount : function()
    {
        var counter = parseInt(getCookie("whp_likec"));
        if (isNaN(counter))
        {
            counter = 0;
        }
        return counter;
    },

    getSharesCount : function()
    {
        var counter = parseInt(getCookie("whp_shrc"));
        if (isNaN(counter))
        {
            counter = 0;
        }
        return counter;
    },



    trackLike: function()
    {
        var counter = getCookie("whp_likec");
        if (isNaN(counter))
        {
            counter = 0;
        }
        counter++;
        setCookie("whp_likec", counter, 60*1000);
    },


    trackComment: function(_reply)
    {
        var counter = getCookie("whp_comc");
        if (isNaN(counter))
        {
            counter = 0;
        }
        counter++;
        setCookie("whp_comc", counter, 60*1000);


        if (!this.trackPermission)
            return false;
        var reply = _reply == true;


        log("WHP/stats : Track comment reply = ["+reply+"]");

        if (reply)
        {
            _gaq.push(['_trackEvent', 'Photo', 'reply']);
        }else{
            _gaq.push(['_trackEvent', 'Photo', 'comment']);
        }
    },

    trackShare : function(_param, _id)
    {
        if (_param == "SHARE_FACEBOOK")
        {
            var counter = getCookie("whp_shrc");
            if (isNaN(counter))
            {
                counter = 0;
            }
            counter++;
            setCookie("whp_shrc", counter, 60*1000);
        }

        if (!this.trackPermission)
            return false;


        var _social = "";
        if (_param == "SHARE_FACEBOOK")
        {
            _social = "facebook";
        }else if (_param == "SHARE_PINTEREST")
        {
            _social = "pinterest";
        }else if (_param == "SHARE_TWITTER")
        {
            _social = "twitter";
        }


        $.ajax({
            url:WHP.netcalls.shareCallSvr,
            data : { r : Math.random(), photo :  _id, social : _social },
            timeout:WHP.netTimeOut,
            success:bind(function (e) { log("trackServer success! ["+_social+"] ["+_id+"]");}, this)
        });


        log("WHP/stats : Track share = ["+_param+"]");
        _gaq.push(['_trackEvent', 'Photo', 'share', _param]);
    },

    trackTimeline : function(_main, _N)
    {
        if (!this.trackPermission)
            return false;
        var mainStr = "USER_TIMELINE_";
        if (_main)
            mainStr = "MAIN_TIMELINE_";


        log("WHP/stats : Track timeline ["+mainStr+_N+"]");
        _gaq.push(['_trackEvent', 'Timeline', 'PagesLoaded', mainStr+_N, _N]);
    },

    trackNotifications : function(_N)
    {
        if (!this.trackPermission)
            return false;
        log("WHP/stats : Track notifications loaded ["+_N+"]");
        _gaq.push(['_trackEvent', 'Notifications', 'PagesLoaded', "PAGES_LOADED_"+_N, _N]);
    },




    trackDownload : function(_param)
    {
        if (!this.trackPermission)
            return false;
        log("WHP/stats : Track download ["+_param+"]");
        _gaq.push(['_trackEvent', 'Download', 'click', _param]);
    },




    trackEmptyTimeline : function(_main)
    {
        if (!this.trackPermission)
            return false;
        var mainStr = "SHOW_TIMELINE_USER_EMPTY";
        if (_main)
            mainStr = "SHOW_TIMELINE_MAIN_EMPTY";

        log("WHP/stats : Track empty timeline ["+mainStr+"]");
        _gaq.push(['_trackEvent', 'Download', 'Views', mainStr]);
    },

    trackPhotoPlateShow : function()
    {
        if (!this.trackPermission)
            return false;
        var mainStr = "SHOW_PHOTO_PAGE_PLATE";
        log("WHP/stats : Track show plate []");
        _gaq.push(['_trackEvent', 'Download', 'Views', mainStr]);
    },

    trackDownloadButtonMenu : function(_new)
    {
        if (!this.trackPermission)
            return false;
        if (!_new)
            var mainStr = "SHOW_DOWNLOAD_MENU"
        else
            var mainStr = "SHOW_DOWNLOAD_MENU_NEW";

        log("WHP/stats : Track download button click ["+mainStr+"]");
        _gaq.push(['_trackEvent', 'Download', 'Views', mainStr]);
    },

    trackEmptyStories : function()
    {
        if (!this.trackPermission)
            return false;
        var mainStr = "SHOW_EMPTYSTORIES_DOWNLOAD";
        log("WHP/stats : Track empty stories ["+mainStr+"]");
        _gaq.push(['_trackEvent', 'Download', 'Views', mainStr]);
    },

    trackShowMainButton : function()
    {
        if (!this.trackPermission)
            return false;
        var mainStr = "SHOW_MAIN_DOWNLOAD";
        log("WHP/stats : Track empty stories ["+mainStr+"]");
        _gaq.push(['_trackEvent', 'Download', 'Views', mainStr]);
    },

    trackXclick : function()
    {
        if (!this.trackPermission)
            return false;
        var mainStr = "SHOW_CLICK_CLOSE_PLATE";
        log("WHP/stats : Track X click service message ["+mainStr+"]");
        _gaq.push(['_trackEvent', 'Download', 'Views', mainStr]);
    },

    trackShuffle : function()
    {
        if (!this.trackPermission)
            return false;
        var N = parseInt(getCookie("whpsc"));
        if (isNaN(N))
            N = 0;
        N++;
        setCookie("whpsc", N, 1000);

        log("WHP/stats : click rnd ["+N+"]");
        _gaq.push(['_trackEvent', 'Other', 'Shuffle', "click", N]);


    }

}







WHP.pages.user = {
	urlStr : "user",
	title : "User",
	rndEnable : false,
	inited : false,
	mainObject : null,
	params : null,
	
	
	curUserId : 0,
	userObject : null,
	avatarPic : null,
	
	follow : false,
	subscribersCount : 0,
	subscriptionsCount : 0,
	pointsCount : 0,
	
	bk : null,
	
	
	mainObject : null,	
	
	//states
	timelineObject : null,	
	timelineCont : null,
	
	storiesObject : null,
	storiesCont : null,
	
	subscribersObject : null,
	subscribersCont : null,
	
	subscriptionsObject : null,
	subscriptionsCont : null,
	
	
	
	followButton : null,
	
	bkImage : null,
	bkContainer : null,
	
	timelineButton : null,
	storiesButton : null,
	privateButton : null,
	
	
	states : [],
	curState : -1,
	defaultState : 0,

    restoreParams : null,


	init: function ()
	{
		this.mainObject = id$('user');
		
		//fedd object init
		this.timelineCont = $(this.mainObject).find(".timeline_box");		
		this.timelineObject = whp_timeline_proto();		
		this.timelineObject.prefix = this.urlStr;
		this.timelineObject.lastposRelated = false;
		this.timelineObject.showEvents = false;
		this.timelineObject.displayLastVisit = false;
		this.timelineObject.controlCanvas = false;
        this.timelineObject.showLoadingOnstart = true;
        this.timelineObject.parent = this;
		this.timelineObject.init( this.timelineCont );
		
		
		this.storiesCont = $(this.mainObject).find(".rolloutstory_box");		
		this.storiesObject = whp_rolloutstory_proto();
		this.storiesObject.init( this.storiesCont );
		
		var fButton = $(this.mainObject).find(".profile_black_plate2");
		$(fButton[1]).click(bind(function() { this.detectState("subscribers"); },this));
		$(fButton[0]).click(bind(function() { this.detectState("subscriptions"); },this));
		
		var pButton = $(this.mainObject).find(".profile_black_plate").css({display : 'none'});
		$(pButton).click(bind( function (e) {this.hideSubWindows(); this.pointsHelper.show(); cancelEvent(e);}, this));
		
		
		
		this.subscribersCont = $(this.mainObject).find(".subscribers_box");		
		this.subscribersObject = whp_subscribers_proto();
		this.subscribersObject.onSubscribe = bind(this.onSubscribeCallback, this);
		this.subscribersObject.onDeSubscribe = bind(this.onSubscribeCallback, this);
		this.subscribersObject.init( this.subscribersCont );
        this.subscribersObject.onDataLoaded = bind(this.onSubscribeData, this);
		
		
		
		this.subscriptionsCont = $(this.mainObject).find(".subscriptions_box");		
		this.subscriptionsObject = whp_subscribers_proto();
		this.subscriptionsObject.onSubscribe = bind(this.onSubscriptionCallback, this);
		this.subscriptionsObject.onDeSubscribe = bind(this.onSubscriptionCallback, this);
		this.subscriptionsObject.init( this.subscriptionsCont );
        this.subscriptionsObject.onDataLoaded = bind(this.onSubscriptionsData, this);
		///////////////////
		
		
		this.followButton = $(this.mainObject).find(".control_button");
		this.followButton.click(bind(this.clickFollowBut, this));
		
		this.bkImage = $(this.mainObject).find(".profile_background_img");
		this.bkContainer = $(this.mainObject).find(".profile_background_cont");
		
		var a = null;
		
		//setup buttons
		this.timelineButton = $(this.mainObject).find(".profile_sub_timeline_0");
		this.timelineButton.click(bind(function() { this.detectState(""); },this));
		
		this.storiesButton = $(this.mainObject).find(".profile_sub_stories_0");
		this.storiesButton.click(bind(function() { this.detectState("stories"); },this));

		
		
		//set up states
		//timeline
        a = { 	N : 0,
            urlPrefix : "",
            show : bind(function()
            {
                //WHP.stats.trackPageChange("/"+this.urlStr+"/"+this.curUserId+"/");
                this.timelineCont.css({ display : 'block' });
                this.timelineObject.show(0);
            }, this),
            hide : bind(function()
            {
                this.timelineObject.hide();
                this.timelineCont.css({ display : 'none' });
            }, this),
            restore : bind(function()
            {
                if (WHP.controller.removedList.length>0)
                {
                    this.timelineObject.rebuildTimeline(WHP.controller.removedList, this.restoreParams);
                }else{
                    this.timelineObject.restore();
                }

                this.timelineCont.css({ display : 'block' });
            }, this),
            cont : this.timelineCont,

            button : this.timelineButton,
            classPrefix : "profile_sub_timeline_"
        }
        this.states.push(a);

        //stories
        a = { 	N : 1,
            urlPrefix : "stories",
            show : bind(function()
            {
                //WHP.stats.trackPageChange("/"+this.urlStr+"/"+this.curUserId+"/stories/");
                this.storiesCont.css({ display : 'block' });
                this.storiesObject.show();
            }, this),
            hide : bind(function()
            {
                this.storiesObject.hide();
                this.storiesCont.css({ display : 'none' });
            }, this),
            restore : bind(function()
            {
                if (WHP.controller.removedList.length>0)
                {
                    this.storiesObject.show();
                }else{
                    this.storiesObject.restore();
                }
                this.storiesCont.css({ display : 'block' });
            }, this),
            cont : this.storiesCont,

            button : this.storiesButton,
            classPrefix : "profile_sub_stories_"
        }
        this.states.push(a);

        //subscribers
        a = { 	N : 2,
            urlPrefix : "subscribers",
            show : bind(function()
            {
                //WHP.stats.trackPageChange("/"+this.urlStr+"/"+this.curUserId+"/subscribers/");
                this.subscribersCont.css({ display : 'block' });
                this.subscribersObject.show();
            }, this),
            hide : bind(function()
            {
                this.subscribersObject.hide();
                this.subscribersCont.css({ display : 'none' });
            }, this),
            restore : bind(function()
            {
                this.subscribersObject.restore();
                this.subscribersCont.css({ display : 'block' });
            }, this),
            cont : this.subscribersCont,

            button : null,
            classPrefix : null
        }
        this.states.push(a);

        //subscriptions
        a = { 	N : 3,
            urlPrefix : "subscriptions",
            show : bind(function()
            {
                //WHP.stats.trackPageChange("/"+this.urlStr+"/"+this.curUserId+"/subscriptions/");
                this.subscriptionsCont.css({ display : 'block' });
                this.subscriptionsObject.show();
            }, this),
            hide : bind(function()
            {
                this.subscriptionsObject.hide();
                this.subscriptionsCont.css({ display : 'none' });
            }, this),
            restore : bind(function()
            {
                this.subscriptionsCont.css({ display : 'block' });
                this.subscriptionsObject.restore();
            }, this),
            cont : this.subscriptionsCont,

            button : null,
            classPrefix : null
        }
        this.states.push(a);


        this.resetRestore();
		
		this.curState = 0;
		this.defaultState = 0;
		
		this.pointsHelper.init( this.mainObject );
		
		this.inited = true;
	},
	
	hideSubWindows : function ()
	{
		WHP.pages.user.pointsHelper.hide();
	},

    onSubscriptionsData : function(resp)
    {
        var respC = resp.followers;
        if (!respC)
            respC = resp.followings;

        this.subscriptionsCount = respC.total;
        this.setFollowersLabels();
    },

    onSubscribeData : function(resp)
    {
        var respC = resp.followers;
        if (!respC)
            respC = resp.followings;

        this.subscribersCount = respC.total;
        this.setFollowersLabels();
    },

	show: function (_q)
	{
		//_q - query string
		var q = _q;
		if (!q)
			q = "/";		
		var params = q.split("/");
		var userId = parseInt(params[0]);
		if (isNaN(userId))
		{
			log("WHP/user : parametres error");
			this.curPageId = null;
			WHP.controller.showErrorPage(2);
			return false;
		}
		this.params = params;

        this.resetRestore();
		
			
		if (WHP.auth.status)
		if (userId == WHP.auth.status.id)
		{
            WHP.controller.getPage(WHP.controller.pages[3].urlStr+"/"+q);
            return false;
		}
		
		
		
		this.curUserId = userId;	
		this.timelineObject.controlUrl = WHP.netcalls.timelineCallUrl+"?user="+userId;
		this.storiesObject.controlUrl = WHP.netcalls.storiesUserCall+"?user="+userId;
		
		
		this.subscribersObject.controlUrl = WHP.netcalls.followersCall+"?user="+userId;
		this.subscriptionsObject.controlUrl = WHP.netcalls.followingsCall+"?user="+userId;


		this.getProfile();
	},

    onContentHeightChange : function(e)
    {
        if (this.restoreParams.setScroll)
        {
            window.scrollTo(0,this.restoreParams.scrollpos);
            WHP.menu.setShadow(this.restoreParams.scrollpos);
            this.restoreParams.setScroll = false;
        }
    },

    resetRestore : function()
    {
        this.restoreParams = {
            scrollpos : 0,
            setScroll : false,
            user : 0
        };
    },

    //std for each module control functions
    restore: function (e)
    {
        //_q - query string
        var q = e;
        if (!q)
            q = "/";
        var params = q.split("/");
        this.params = params;
        var userId = parseInt(params[0]);

        log("RESTORE!!! restore id =["+userId+"] ["+this.restoreParams.user+"] userId = ["+this.curUserId+"]");


        if (WHP.auth.status)
        if (userId == WHP.auth.status.id)
        {
            WHP.controller.getPage(WHP.controller.pages[3].urlStr+"/"+q, true);
            //WHP.controller.pages[3].restore(e);

            //log("RESTORE PROFILE");
            return false;
        }

        if (userId!=this.restoreParams.user)
        {
            this.show(e);
        }


        if (this.restoreParams.timelineRestoreResponse)
        {
            this.timelineObject.onData(this.restoreParams.timelineRestoreResponse,  this.timelineObject.startPage);
            this.restoreParams.timelineRestoreResponse = null;
        }

        this.restoreParams.setScroll = true;

        WHP.controller.showCanvas();

        var chStr = "";

        if (params.length>1)
            chStr = params[1];

        if (this.states[this.curState].urlPrefix != chStr)
        {
            this.detectState(chStr, true);
        }else{
            //restore prototypes
            this.states[this.curState].restore();
        }


        setTimeout(bind(function() {
            if (this.restoreParams.setScroll)
            {
                window.scrollTo(0,this.restoreParams.scrollpos);
                WHP.menu.setShadow(this.restoreParams.scrollpos);
                this.restoreParams.setScroll = false;
            }
        }, this), 100)
    },


    hide: function (_q)
    {
        this.restoreParams.scrollpos = $(document).scrollTop();
        this.restoreParams.user = this.curUserId;

		this.timelineObject.hide();
        this.subscribersObject.hide();
        this.subscriptionsObject.hide();
        this.storiesObject.hide();
	},
	
	
	getProfile: function ()
	{
		$.ajax({
			  url: WHP.netcalls.getProfileCall,
              data : { user : this.curUserId, r : Math.random() },
			  timeout : WHP.netTimeOut,
			  success: bind(this.onData, this),
			  error: bind(this.onError, this)
		});
	},
	
	
	onData : function (response, status, xhr)
	{
        if (!this.active)
            return false;

		window.scroll(0,0);
		var resp = getObjectJson(response);		
		if (resp.error)
		{
			log("WHP/pages/user : get picture error = ["+resp.error.code+"]");
			if (!WHP.errors.hasNetError(resp))
			{
				WHP.controller.showErrorPage();
			}
			return false;
		}	
		
		this.userObject = resp.user;
		this.timelineObject.userObject = this.userObject;
		
		
		
		this.setProfile(resp);
		this.setTitle(resp);
		WHP.controller.showCanvas();
		
		var qStr = "";
		if (this.params.length>1)
			qStr = this.params[1];

		this.detectState(qStr);
		//this.timelineObject.show(0);
		//this.storiesObject.show(0);
	},
	
	
	onError : function (e)
	{
		log("WHP/pages/user: Error while loading actual data! : ["+e+"]");
	},	
	
	
	setProfile : function (resp)
	{
		if (resp.user.photo)
			ava = resp.user.photo['i106x106'];
		this.setAvatar(ava);	
				
		var a = $(this.mainObject).find( ".profile_name_label" );	
		a.text(resp.user.name);
		
		this.follow = resp.user.follow;
		this.setButtonLabel();

		
	
		this.subscribersCount = resp.user.followers_count;
		this.subscriptionsCount = resp.user.followings_count;
		this.pointsCount = resp.user.points ;
		
		this.subscribersObject.setName("Subscribers");
		this.subscriptionsObject.setName("Subscriptions");
		
		
		this.bk = resp.user.background;
        this.setBk();
	
		this.setFollowersLabels();
		//points
		
		
		a = $(this.mainObject).find( ".profile_avatar_image" );
		var ava = null;
	},
	
	setBk : function ()
	{
		var _link = "http://"+WHP.domain+"/gui/profile_default_bk.jpg";
		if (this.bk)
		{
			_link = this.bk['i1000x314'];
		}
        setImageOnload(this.bkImage, _link, this.bkContainer );

	},
	
	
	setFollowersLabels : function ()
	{
		var lcds = $(this.mainObject).find(".profile_n_label");
		this.followersLCD = $(lcds[1]);
		this.followingsLCD = $(lcds[0]);
		this.pointsLCD = $(lcds[2]);
		
		//followers
		this.followersLCD.text(this.subscribersCount + " subscribers");
		if (this.subscribersCount==1)
			this.followersLCD.text(this.subscribersCount + " subscriber");
			
		//following
		this.followingsLCD.text(this.subscriptionsCount + " subscriptions");
		if (this.subscriptionsCount==1)
			this.followingsLCD.text(this.subscriptionsCount + " subscription");
			
		this.pointsLCD.text(this.pointsCount + " points");
		if (this.pointsCount==1)
			this.pointsLCD.text(this.pointsCount + " point");
	},
	
	
	setAvatar : function (_str)
	{
		if (!_str)
		{
			if (this.avatarPic)
			{
				$(this.avatarPic).remove();
				this.avatarPic = null;
			}
		}else{
			if (this.avatarPic)
			{
				$(this.avatarPic).remove();
				this.avatarPic = null;
			}
			
			var a  = $(this.mainObject).find( ".profile_avatar_image_cont" );	
			
			this.avatarPic = document.createElement("img");
			setClass(this.avatarPic, "profile_avatar_img");	
			this.avatarPic.src = _str;
			a.append(this.avatarPic);
		}
	},
	
	
	setButtonLabel: function (_q)
	{
		var labl = $(this.followButton).find(".control_button_label");
		if (WHP.auth.status)
		{
			
			if (this.follow)
				labl.html("Remove")
			else
				labl.html("Subscribe");
			
			//this.followButton.css({ visibility : 'visible' });
		}else{
			labl.html("Subscribe");
			//this.followButton.css({ visibility : 'hidden' });
		}		
	},
	
	
	clickFollowBut: function (e)
	{
		if (!WHP.auth.status)
		{
			WHP.loginMenus.showLoginMenu2();
			return false;	
		}
		
		var call = WHP.netcalls.followCall;
		
		if (this.follow)
        {
			call = WHP.netcalls.unfollowCall;
        }else{
            WHP.opengraph.makeFolowAction(this.curUserId);
        }
		
		var labl = $(this.followButton).find(".control_button_label");
		labl.html("<div class='button_loading'></div>");	
		$.ajax({
			  url: call+"?r="+Math.random() ,
              data : { user : this.curUserId },
			  timeout : WHP.netTimeOut,
			  success: bind(this.onFollowButCall, this),
			  error: bind(this.onError, this)
		});
	},

    onSubscribeCallback : function (_a)
    {
        this.subscriptionsCount = this.subscriptionsCount+_a;
        this.setFollowersLabels();
    },

    onSubscriptionCallback : function (_a)
    {
        this.subscriptionsCount = this.subscriptionsCount+_a;
        this.setFollowersLabels();
    },

	
	
	onFollowButCall: function (response)
	{
		var resp = getObjectJson(response);			
		if (resp.error)
		{
			WHP.errors.hasNetError(resp);
			return false;
		}


		if (resp.status == "OK")
		{
			this.follow = !this.follow;
			
			if (this.follow)
				this.subscribersCount++
			else
				this.subscribersCount--;
			
			this.setFollowersLabels();
			this.setButtonLabel();
		}
	},
	
	setTitle : function (resp)
	{
		this.title = resp.user.name;	 
		WHP.controller.setTitle(); 
	},
	
	detectState : function (q, _NotChangeLink)
	{
		var startState = this.curState;
		var newState = this.defaultState;
		for (var i=0; i<this.states.length; i++)
		{
			if (this.states[i].urlPrefix == q)
			{
				newState = i;
				break;
			}
		}

		
		//switch to
		this.curState = newState;
		for (var i=0; i<this.states.length; i++)
		{
			if (i == newState)
			{
				this.states[i].show();
				if (this.states[i].button)
					setClass(this.states[i].button,  this.states[i].classPrefix+"1");				
			}else{
				this.states[i].hide();
				if (this.states[i].button)
					setClass(this.states[i].button,  this.states[i].classPrefix+"0");
			}
		}
		

		if (startState != newState)
		{
			var stateStr = "";
			if (this.curState>-1)
			{
				if (this.states[this.curState].urlPrefix != "")
					stateStr  = this.states[this.curState].urlPrefix+"/";
			}
			var urla = this.urlStr+"/"+this.curUserId+"/"+stateStr;
            if (!_NotChangeLink)
            {
                setLink( "http://" + WHP.domain + "/" + urla);
            }
		}

        WHP.shares.hideAct2();
		//WHP.resetH();
	},
	
	
	
	pointsHelper : {
	
		inited : false,
		
		windCont : null,
		linkElem : null,
		
				
		//init function
		init: function (_el)
		{		
			this.linkElem = _el
			this.windCont = $(_el).find( ".points_window" ).get()[0];	
			this.inited = true;
		},
		
		show: function ()
		{
			this.windCont.style.display = "block";
			this.setPos();		
			//WHP.resetH();
		},
		
		setPos: function ()
		{
			this.windCont.style.left = -(this.windCont.offsetWidth)*0.5 + 20 +'px';
			this.windCont.style.top = 38+'px';
		},
		
		clickButton: function (e)
		{
			if (this.windCont.style.display == "none")
			{
				//show
                this.show();
			}else{
				//hide
				this.hide();
			}
			return cancelEvent(e);
		},
		hide: function ()
		{
			this.windCont.style.display = "none";
		}
	}

}


WHP.pages.stories = {
    //controller parametres
    urlStr:"stories",
    title:"Stories",
    rndEnable:true,
    inited:false,

    mainObject:null,

    responseObject : null,

    headElements:[],
    headCanvas:null,
    curElem:0,

    contentElements:[],


    storyIcoTemplate:null,

    dailyStoryTempl : null,


    storiesCont:null,
    storiesObject:null,
    storiesVobject:null,
    storyTemplateCanvas : null,

    storyTemplate:null,
    smallStoryTemplate:null,


    paginL : null,
    paginR : null,
    dailyStoriesCont:null,
    dailyStoriesCanvas:null,
    dailyStoriesElements : [],
    dailyStoriesObject:null,
    dailystoriesTemplate:null,
    dailyOffset : 0,
    dailyPagin : null,

    lastCallN:0,
    loadingBar : null,


    restoreParams : null,

    showParams : {
        active : false,
        catId : -1,
        subCat : -1,

        scrollActive : false,
        scrollTo : 0
    },


    //init function
    init:function () {
        this.mainObject = id$('stories');
        this.canvas = $(this.mainObject).find(".stories_box");

        this.storyIcoTemplate = $('#story_menu_li').clone();
        this.storyIcoTemplate.removeAttr('id');

        this.dailyStoryTempl = $('#template_daily_elem').clone();
        this.dailyStoryTempl.removeAttr('id');


        this.loadingBar = $(this.mainObject).find(".notifications_loading_tab");
        this.loadingBar.css({ display : 'none', margin : 'auto'});




        this.headCanvas = $(this.mainObject).find(".stories_icons_cont");
        this.headCanvas.timer = new Timer(1000 / 30, 10);
        this.headCanvas.timer.onTimerEvent = bind(this.timerMoveVevent, this);
        this.headCanvas.cP = 0;
        this.headCanvas.p0 = 0;
        this.headCanvas.p1 = 0;

        this.dailystoriesTemplate = $('#dailystories').clone();
        this.dailystoriesTemplate.removeAttr('id');
        this.dailyStoriesCanvas = this.dailystoriesTemplate.find(".story_canvas");

        this.paginL = $( this.dailystoriesTemplate ).find( ".std_paging_left" );
        this.paginR = $( this.dailystoriesTemplate ).find( ".std_paging_right" );

        this.paginR.click(bind(function () { log("R"); this.getDailyPage(1); },this));
        this.paginL.click(bind(function () { this.getDailyPage(-1); },this));
        this.dailyPagin = $( this.dailystoriesTemplate ).find( ".paging_table");


        this.storiesVobject = $(this.mainObject).find(".stories_head_v");


        this.storyTemplate = $('#dailystories').clone();
        this.storyTemplate.removeAttr('id');
        this.storyTemplateCanvas = this.storyTemplate.find(".story_canvas");
        this.storyTemplate.find(".paging_table").remove();


        this.smallStoryTemplate = $("#template_story_elem").clone();
        this.smallStoryTemplate.removeAttr('id');

        this.storiesCont = $(this.mainObject).find(".stories_content");
        this.storiesCont.append(this.storyTemplate);


        this.dailyStoriesCont = $(this.mainObject).find(".dailystories_content");
        this.dailyStoriesCont.append(this.dailystoriesTemplate);

        this.resetRestore();

        this.inited = true;
    },


    //std for each module control functions
    show:function (_q) {
        //get parametres
        var q = _q;
        if (!q)
            q = "";


        var params = q.split("/");

        if (params.length>0)
        if (params[0]!="")
        {
            //get cat
            this.showParams.active = true;
            this.showParams.catId = params[0];
            if (params.length>1)
            {
                this.showParams.subCat = parseInt(params[1]);
                if (isNaN(this.showParams.subCat))
                {
                    this.showParams.subCat = -1;
                }
            }

        }else{
            this.showParams.active = false;
        }



        //get parametresf
        this.resetRestore();
        this.clearCanvas();
        this.loadCats();
    },

    loadCats:function () {
        //clear canvas
        this.jqxhr = $.ajax({
            url:WHP.netcalls.storiesCall,
            data:{ r : Math.random() },
            timeout:WHP.netTimeOut,
            success:bind(this.onData, this),
            error:bind(this.onError, this)
        });
    },
    onData:function (response) {
        WHP.controller.scrollToPos(0, 0);

        var resp = getObjectJson(response);
        if (resp.error) {
            log("WHP/pages/stories : error while loading page data! Err =[" + response + "]");
            if (!WHP.errors.hasNetError(resp)) {
                WHP.controller.showErrorPage();
            }
            return false;
        }
        this.responseObject = resp;

        if (false)
        {
            var orderer = [
                { id : 1, n : 0, ord : 0},  //About me
                { id : 2, n : 1, ord : 1},  //Friends and family
                { id : 3, n : 2, ord : 2},  //Home
                { id : 4, n : 3, ord : 4},  //Work and study
                { id : 5, n : 4, ord : 3},  //Places
                { id : 6, n : 5, ord : 5}]; //City

            orderer = orderer.sort(function(a, b){
                return (a.ord > b.ord) ? 1 : -1;
            });


            var nA = [];
            for (var i = 0; i<orderer.length; i++)
            {
                nA.push(resp.storycats[ orderer[i].n ]);
            }
            resp.storycats = nA;
        }


        this.clearCanvas();
        //setClass(element_div.ico, "stories_ico_"+resp.id);
        for (var i = 0; i < resp.storycats.length; i++) {
            var elem = this.getIcon();
            var obj = resp.storycats[i];

            elem.id = obj.id;
            elem.label.text(obj.name);
            elem.parent = this;
            //chrome bk bug

            setClass(elem.ico, "stories_ico_" + obj.id);
            elem.ico.css({ 'background-image': 'none'});

            this.headCanvas.append(elem);
            this.headElements.push(elem);
        }


        setTimeout( bind(function(){
            for (var i=0; i< this.headElements.length; i++)
            {
                this.headElements[i].ico.css({ 'background-image': ''});
            }
        },this), 150);


        //add Daily story
        var elem = this.getIcon();
        elem.label.text("Daily story");
        elem.id = "daily";
        elem.parent = this;
        setClass(elem.ico, "stories_ico_7")
        this.headCanvas.append(elem);
        this.headElements.push(elem);


        for (var i = 0; i < this.headElements.length; i++) {
            var a = this.headElements[i];
            a.curN = new Number(i);
            a.daily = false;
            a.click(bind(this.headElemClick, a));
        }


        this.headElements[0].css({ 'margin-left':12 + 'px'});
        this.headElements[this.headElements.length - 1].css({ 'margin-right':12 + 'px'});
        this.headElements[this.headElements.length - 1].daily = true;


        WHP.controller.showCanvas();
        //load content

        //get cur elem by id
        if (this.showParams.active)
        {
            this.curElem = this.getCatById(this.showParams.catId);
            if (this.curElem ==-1)
                this.curElem = 0;
        }else{
           this.curElem = 0;
        }

        this.setPosFast(this.curElem);
        this.headElements[this.curElem].click();
        //this.getContent(this.headElements[this.curElem].id);

        this.storiesVobject.css({ display:'block'});
        WHP.controller.setTitle();
        //WHP.resetH();
    },

    getCatById : function(_id)
    {
        var retN = -1;
        for (var i=0; i<this.headElements.length; i++)
        {
            if (_id == this.headElements[i].id)
            {
                retN = i;
                break;
            }
        }

        return retN;
    },

    onContentHeightChange : function(e)
    {
        if (this.restoreParams.setScroll)
        {
            window.scrollTo(0,this.restoreParams.scrollpos);
            WHP.menu.setShadow(this.restoreParams.scrollpos);
            this.restoreParams.setScroll = false;
        }


        if (this.showParams.scrollActive && this.showParams.active)
        {
            this.showParams.scrollActive = false;
            var scrollPos = elementOffset(this.contentElements[this.showParams.scrollTo]).top;
            //WHP.smoothScrollTo(0, scrollPos);
        }
    },

    restore: function (e)
    {
        this.restoreParams.setScroll = true;
        WHP.controller.showCanvas();
    },

    hide : function()
    {
        this.restoreParams.scrollpos = $(document).scrollTop();
    },

    resetRestore : function()
    {
        this.restoreParams = {
            scrollpos : 0,
            setScroll : false
        };
    },



    onError:function (response, status, xhr) {
        log("WHP/pages/stories : Error while loading actual data! Err = [" + response + "]");
    },


    getIcon:function () {
        var element_div = this.storyIcoTemplate.clone();
        element_div.ico = element_div.find(".profile_menu_li_ico");
        element_div.label = element_div.find(".profile_menu_li_text");

        return element_div;
    },

    setPosFast:function (_N) {
        WHP.shares.hideAct2();
        this.setLabelsActive(_N);
        var a = 124;
        var b = 57;

        var left = a * _N + b;
        this.curElem = _N;
        this.storiesVobject.css({ left:left + 'px'});
    },

    headElemClick:function (e) {
        WHP.shares.hideAct2();

        var curN = parseInt(this.curN);
        this.parent.setPosMotion(curN);

        if (this.daily)
        {
            setLinkReplace( WHP.links.getStoriesLinkDaily(), this.restoreParams);
            this.parent.getContentDaily();
        }else{
            if (this.loadingBar)
                this.loadingBar.css({ display : 'none'});
            setLinkReplace( WHP.links.getStoriesLink(this.id), this.restoreParams);
            this.parent.getContent(this.id);
        }

        WHP.shares.hideAct2();

    },

    timerMoveVevent:function (e) {
        var A = e.currentCount / e.repeatCount;
        var B = (Math.sin(Math.PI * (A - 0.5)) + 1) * 0.5;

        this.headCanvas.cP = (1 - B) * this.headCanvas.p0 + B * this.headCanvas.p1;
        this.storiesVobject.css({ 'left':this.headCanvas.cP + 'px'});
    },

    setLabelsActive : function(_N)
    {
        //profile_menu_li_active
        for (var i=0; i<this.headElements.length; i++)
        {
            if (_N == i)
            {
                setClass(this.headElements[i], "profile_menu_li_active");
            }else{
                setClass(this.headElements[i], "profile_menu_li");
            }
        }
    },

    setPosMotion:function (_N) {
        //WHP.stats.trackPageChange("/"+this.urlStr+"/"+this.headElements[_N].id+"/");
        this.setLabelsActive(_N);
        var a = 124;
        var b = 57;

        var left1 = this.headCanvas.cP;
        var left2 = a * _N + b;

        this.headCanvas.p0 = left1;
        this.headCanvas.p1 = left2;
        this.curElem = _N;

        this.headCanvas.timer.reset();
        this.headCanvas.timer.start();
    },

    getContent:function (_N) {
        this.lastCallN++;
        var k = this.lastCallN;
        this.clearContent();


        this.dailyStoriesCont.css({display : 'none'});
        this.storiesCont.css({display : 'block'});

        this.loadingBar.css({ display : 'none'});
        this.getContentResponse(this.responseObject.storycats[_N-1], k);
    },

    getContentResponse:function (response, _N) {
        if (_N != this.lastCallN)
            return false;

        var resp = getObjectJson(response);
        if (resp.error) {
            log("WHP/pages/stories : error while loading page data! Err =[" + response + "]");
            return false;
        }

        for (var i=0; i< resp.storysets.length; i++)
        {
            //log("["+i+"] = ["+resp.tree[0].childs[i]+"]");
            var element_div = this.newStory(resp.storysets[i]);

            this.storyTemplateCanvas.append(element_div);
            this.contentElements.push(element_div);
        }
        //WHP.resetH();
        addIntelloLinks(this.storyTemplateCanvas);
        return true;
    },


    getSubCatById : function(_id)
    {
        var ret = -1;
        for (var i=0; i<this.contentElements.length;i++)
        {
            if (this.contentElements[i].story_id == _id)
            {
                ret = i;
                break;
            }
        }
        return ret;
    },

    clearDailyCanvas:function()
    {
        while (this.dailyStoriesElements.length > 0) {
            var a = this.dailyStoriesElements.pop();
            a.remove();
        }
        $(this.paginR).addClass("hidden");
        $(this.paginL).addClass("hidden");
        this.dailystoriesTemplate.css({display : 'none'});
    },

    clearContent:function () {
        while (this.contentElements.length > 0) {
            var a = this.contentElements.pop();
            a.remove();
        }

    },

    clearCanvas:function () {
        //clear Content
        //clear head
        while (this.headElements.length > 0) {
            var a = this.headElements.pop();
            a.remove();
        }
        this.storiesVobject.css({ display:'none'});
    },



    createSmallStory:function (_resp) {
        var element_div = this.smallStoryTemplate.clone();

        element_div.label = $(element_div).find(".story_label_small");
        element_div.image = $(element_div).find(".story_img");
        element_div.mainImage  =  $(element_div).find(".template_story_elem_img");

        element_div.image.mouseenter(bind(this.mouseE, element_div));
        element_div.image.mouseleave(bind(this.mouseO, element_div));


        element_div.image_link = $(element_div).find(".feed_photo_link");
        element_div.new_ico = $(element_div).find(".story_new_ico");
        element_div.story_bk_fader = $(element_div).find(".story_bk_fader");

        element_div.image_src = _resp["i320x80"];

        setImageOnload(element_div.mainImage, element_div.image_src, null, bind(this.miniLoaded, element_div));

        element_div.label.text(_resp.name).css({ color:"#222"});
        element_div.id = _resp.id;

        element_div.image_link.attr('href', WHP.links.getScenarioLink(element_div.id));
        element_div.image_link.click(bind(function() { WHP.pages.story.linkBack = true; }, this));

        if (_resp.is_new)
            element_div.new_ico.css({display:'block'});

        return element_div;
    },

    miniLoaded:function () {
        this.story_bk_fader.css({ 'background-image':'url(./resouce/images/public/story_bk_fader.png)'});
        this.image.css({ 'background-image':'none' });
        this.label.css({ 'color' : "#ffffff" });
    },

    rollStory:function (e) {
        this.p0 = this.cP;
        if (this.p1 == 1.0) {
            this.p1 = 0.0;
            this.story_roll_but.shRollBut(false);
        } else {
            this.p1 = 1.0;
            this.story_roll_but.shRollBut(true);
            this.showElementsBlock(true);
        }

        this.timer.reset();
        this.timer.start();


        var scrollPos = elementOffset(this).top-70;
        WHP.smoothScrollTo(0, scrollPos, null, true);

        return cancelEvent(e);
    },

    getContentDaily:function () {
        this.lastCallN++;
        var k = this.lastCallN;
        this.clearContent();
        this.clearDailyCanvas();
        this.loadingBar.css({ display : 'block'});
        this.dailyOffset = 0;
        this.dailyTotal = 0;

        this.dailyStoriesCont.css({display : 'none'});
        this.loadingBar.css({ display : ''});
        this.storiesCont.css({display : 'none'});

        while(this.dailyStoriesElements.length>0)
        {
            var a =  this.dailyStoriesElements.pop();
            a.remove();
        }

        $.ajax({
            url:WHP.netcalls.dailyStories,
            data:{  r:Math.random() , offset : this.dailyOffset, limit : 14 },
            timeout:WHP.netTimeOut,
            success:bind(function (resp) {
                this.getContentDailyResponse(resp, k);
            }, this),
            error:bind(this.onError, this)
        });
    },



    getDailyPage:function (_a) {
        var newOffset = this.dailyOffset + _a*30;

        if ((newOffset>this.dailyTotal) || (newOffset < 0))
            return false;

        this.dailyStoriesCont.css({display : 'none'});
        this.loadingBar.css({ display : ''});

        this.dailyOffset = newOffset;

        this.lastCallN++;
        var k = this.lastCallN;

        while(this.dailyStoriesElements.length>0)
        {
            var a =  this.dailyStoriesElements.pop();
            a.remove();
        }

        $.ajax({
            url:WHP.netcalls.dailyStories,
            data:{  r:Math.random() , offset : this.dailyOffset, limit : 14 },
            timeout:WHP.netTimeOut,
            success:bind(function (resp) {
                this.getContentDailyResponse(resp, k);
            }, this),
            error:bind(this.onError, this)
        });
    },

    getContentDailyResponse:function (response, _N) {
        if (_N != this.lastCallN)
            return false;

        var resp = getObjectJson(response);
        if (resp.error) {
            log("WHP/pages/stories : error while loading page data! Err =[" + response + "]");
            return false;
        }

        this.loadingBar.css({ display : 'none'});
        this.dailyTotal = resp.stories.total;




        for (var i=0; i<resp.stories.list.length; i++)
        {
            //log("["+i+"] = ["+resp.tree[0].childs[i]+"]");
            var element_div = this.newDailyStory(resp.stories.list[i]);

            this.dailyStoriesCanvas.append(element_div);
            this.dailyStoriesElements.push(element_div);
        }


        //WHP.resetH();
        addIntelloLinks(this.dailyStoriesCanvas);
        this.checkDailyPagin();
        this.dailystoriesTemplate.css({display : 'block'});
        this.dailyStoriesCont.css({display : ''});


        return true;
    },

    checkDailyPagin : function ()
    {
        var imageLimit = 30;
        if (this.dailyTotal <= imageLimit)
        {
            this.paginL.addClass("hidden");
            this.paginR.addClass("hidden");
            this.dailyPagin.css({ display : 'none' });
        }else{
            this.dailyPagin.css({ display : '' });
            if (this.dailyOffset==0)
                this.paginL.addClass("hidden");
            else
                this.paginL.removeClass("hidden");

            if (this.dailyOffset >= this.dailyTotal-imageLimit )
                this.paginR.addClass("hidden")
            else
                this.paginR.removeClass("hidden");
        }

    },

    newStory : function (_resp)
    {
        var element_div = this.dailyStoryTempl.clone();
        element_div.label = $(element_div).find(".story_label_small");
        element_div.image = $(element_div).find(".story_img");
        element_div.mainImage = $(element_div).find(".template_story_elem_img");

        element_div.image.mouseenter(bind(this.mouseE, element_div));
        element_div.image.mouseleave(bind(this.mouseO, element_div));
        element_div.line_bottom = element_div.find(".story_bottom_line");
        element_div.line_bottom.css({ visibility: 'hidden' });

        element_div.image_link = $(element_div).find(".feed_photo_link");
        element_div.new_ico = $(element_div).find(".story_new_ico");
        element_div.story_bk_fader = $(element_div).find(".story_bk_fader");

        element_div.image_src = _resp.story["i320x80"];

        element_div.label.text(_resp.name).css({ color:"#222"});
        element_div.image_link.attr('href', WHP.links.getScenarioLink(_resp.story.id));
        element_div.image_link.click(bind(function() { WHP.pages.story.linkBack = true; }, this));


        var newIco = $(element_div).find(".story_new_ico");
        var totalImg = $(element_div).find(".story_total_small");
        totalImg.remove();
        newIco.remove();



        if (_resp.is_new)
        {
            newIco.css({ display : 'block' });
        }else{
            newIco.css({ display : 'none' });
        }
        setImageOnload(element_div.mainImage, element_div.image_src, null, bind(this.miniLoadedDaily, element_div));


        return element_div;
    },

    newDailyStory : function (_resp)
    {
        var element_div = this.dailyStoryTempl.clone();
        element_div.label = $(element_div).find(".story_label_small");
        element_div.image = $(element_div).find(".story_img");
        element_div.mainImage = $(element_div).find(".template_story_elem_img");

        element_div.mOverAlpha = 1.0;
        element_div.mOutAlpha = 1.0;
        element_div.aC = element_div.mOutAlpha;
        element_div.a0 = 0;
        element_div.a1 = 0;
        element_div.timerAlpha = new Timer(1000/30, 4);
        element_div.timerAlpha.onTimerEvent = bind(this.level3alpha, element_div);
        setAlpha(element_div.image, element_div.mOutAlpha);
        element_div.image.mouseenter(bind(this.mouseE, element_div));
        element_div.image.mouseleave(bind(this.mouseO, element_div));
        element_div.line_bottom = element_div.find(".story_bottom_line");
        element_div.line_bottom.css({ visibility: 'hidden' });


        element_div.image_link = $(element_div).find(".feed_photo_link");
        element_div.new_ico = $(element_div).find(".story_new_ico");
        element_div.story_bk_fader = $(element_div).find(".story_bk_fader");

        element_div.image_src = _resp["i320x80"];

        element_div.label.text(_resp.name).css({ color:"#222"});
        element_div.image_link.attr('href', WHP.links.getScenarioLink(_resp.id));
        element_div.image_link.click(bind(function() { WHP.pages.story.linkBack = true; }, this));


        var newIco = $(element_div).find(".story_new_ico");
        var totalImg = $(element_div).find(".story_total_small");
        totalImg.text(_resp.photos_count);



        if (_resp.is_new)
        {
            newIco.css({ display : 'block' });
        }else{
            newIco.css({ display : 'none' });
        }
        setImageOnload(element_div.mainImage, element_div.image_src, null, bind(this.miniLoadedDaily, element_div));


        return element_div;
    },

    mouseE : function()
    {
        if (this.loaded)
            this.line_bottom.css({ visibility: 'visible' });

    },

    mouseO : function()
    {
        if (this.loaded)
            this.line_bottom.css({ visibility: 'hidden' });
    },

    miniLoadedDaily:function () {
        //log("LOADED! = ["+this.image_src+"] ["+ this.story_bk_fader.css( 'background-image')+"] ["+this.image.css('background-image')+"]")
        this.story_bk_fader.css({ 'background-image':'url(./resouce/images/public/story_bk_fader.png)'});
        this.image.css({ 'background-image':'url(' + this.image_src + ')' });
        this.label.css({ 'color' : "#ffffff" });
        this.loaded = true;
    }
}



WHP.pages.profile = {

	urlStr : "profile",

    urlStr2 : "user",
	title : "Profile",
	rndEnable : false,
	inited : false,
	mainObject : null,
	params : null,
	
	
	curUserId : 0,
	userObject : null,
	avatarPic : null,
	
	follow : false,
	subscribersCount : 0,
	subscriptionsCount : 0,
	pointsCount : 0,
	
	bk : null,
	
	
	mainObject : null,	
	
	//states
	timelineObject : null,	
	timelineCont : null,
	
	storiesObject : null,
	storiesCont : null,
	
	subscribersObject : null,
	subscribersCont : null,

    newfacesObject : null,
	subscriptionsObject : null,
	subscriptionsCont : null,


	
	privateObject : null,
	privateCont : null,
	
	
	bkImage : null,
	bkContainer : null,
	
	timelineButton : null,
	storiesButton : null,
	privateButton : null,
	
	
	states : [],
	curState : -1,
	defaultState : 0,

    active : false,

    bkMove : {
        moving : false,

        moveButton : null,
        moveOkButton : null,
        moveCancelButton : null,

        loadInd : null,
        moveInd : null,

        drUgEnable : false,
        timer : new Timer(1000/30, 0),

        bkPos : 0,
        bkStart : 0,

        buttonsCont : null,

        start : {
            x : 0,
            y : 0
        },

        cur : {
            x : 0,
            y : 0
        }
    },


    restoreParams : null,
    window1 : null,



	
		
	init: function ()
	{
		this.mainObject = id$('profile');
		
		//fedd object init
		this.timelineCont = $(this.mainObject).find(".timeline_box");		
		this.timelineObject = whp_timeline_proto();		
		//this.timelineObject.prefix = this.urlStr2+"/"+WHP.auth.status.id;
		this.timelineObject.lastposRelated = false;
		this.timelineObject.showEvents = false;
		this.timelineObject.displayLastVisit = false;
		this.timelineObject.controlCanvas = false;
        this.timelineObject.showLoadingOnstart = true;
        this.timelineObject.parent = this;
        this.timelineObject.showEmpty = true;
		this.timelineObject.init( this.timelineCont );

        this.bkMove.buttonsCont = $(this.mainObject).find(".profile_bk_buttons");
        this.bkMove.deactiveButton = $(this.mainObject).find(".profile_bk_move_control");
        this.bkMove.activeButton = $(this.mainObject).find(".profile_bk_move_control_active");
        this.bkMove.moveButton = $(this.mainObject).find(".profile_bk_move");
        this.bkMove.moveButton.click(bind(this.startMove, this));
        this.bkMove.moveOkButton = $(this.mainObject).find(".profile_bk_ok");
        this.bkMove.moveOkButton.click(bind(this.applyMove, this));
        this.bkMove.moveCancelButton = $(this.mainObject).find(".profile_bk_cancel");
        this.bkMove.moveCancelButton.click(bind(this.cancelMove, this));

        this.moveButtons(0);


        this.bkMove.loadInd = $(this.mainObject).find(".profile_bk_loading");
        this.bkMove.moveInd = $(this.mainObject).find(".profile_bk_move2");

        this.bkMove.deactiveButton.css({ display : 'none' });
        this.bkMove.activeButton.css({ display : 'none' });

        this.bkMove.loadInd.css({ display : 'none' });
        this.bkMove.moveInd.css({ display : 'none' });
		
		
		this.storiesCont = $(this.mainObject).find(".rolloutstory_box");		
		this.storiesObject = whp_rolloutstory_proto();
        this.storiesObject.showEmpty = true;
		this.storiesObject.init( this.storiesCont );
		
		
		this.privateCont = $(this.mainObject).find(".private_box");
		this.privateObject = new whp_feed_proto();	
		this.privateObject.changeUrl = true;
        this.privateObject.useGalleryPhoto = true;
		this.privateObject.init(this.privateCont);	
		
		
		
		var fButton = $(this.mainObject).find(".profile_black_plate2");
		$(fButton[1]).click(bind(function() { this.detectState("subscribers"); },this));
		$(fButton[0]).click(bind(function() { this.detectState("subscriptions"); },this));
		
		var pButton = $(this.mainObject).find(".profile_black_plate").css({display : 'none'});
		$(pButton).click(bind( function (e) {this.hideSubWindows(); this.pointsHelper.shClick(); cancelEvent(e);}, this));
		
		
		
		this.subscribersCont = $(this.mainObject).find(".subscribers_box");		
		this.subscribersObject = whp_subscribers_proto();
		this.subscribersObject.onSubscribe = bind(this.onSubscribeCallback, this);
		this.subscribersObject.onDeSubscribe = bind(this.onSubscribeCallback, this);
		this.subscribersObject.init( this.subscribersCont );
        this.subscribersObject.onDataLoaded = bind(this.onSubscribeData, this);

        this.subscriptionsCont = $(this.mainObject).find(".subscriptions_box");

        this.newfacesObject = whp_newfaces_proto();
        this.newfacesObject.onSubscribe = bind(this.onNewfacesCallback, this);
        this.newfacesObject.onDeSubscribe = bind(this.onNewfacesCallback, this);
        this.newfacesObject.onDataLoad = bind(this.onNewFacesData, this);
        this.newfacesObject.init( this.subscriptionsCont );

		

		this.subscriptionsObject = whp_subscribers_proto();
		this.subscriptionsObject.onSubscribe = bind(this.onSubscriptionCallback, this);
		this.subscriptionsObject.onDeSubscribe = bind(this.onSubscriptionCallback, this);
		this.subscriptionsObject.init( this.subscriptionsCont );
        this.subscriptionsObject.onDataLoaded = bind(this.onSubscriptionsData, this);






        this.window1 = $("#set_name");
        this.window1.buttonShow = $(this.mainObject).find(".edit_name_ico");
        this.window1.buttonShow.click(bind(this.clickChangeName, this));
        this.window1.activeSet = false;
        this.window1.css({ position : 'fixed' });
        this.window1.click(bind(function(event) {
            event.stopPropagation();
        }, this));
        this.window1.errorMessageTimeout = -1;
        this.window1.error_meassage = this.window1.find(".form_error_message");
        this.window1.showErrMsg = bind(function(_txt)
            {
                this.error_meassage.text(_txt);
                this.hideMsg();
            }
            ,this.window1);
        this.window1.hideMsg = bind(function()
            {
                if (this.errorMessageTimeout!=-1)
                    clearTimeout(this.errorMessageTimeout);
                this.errorMessageTimeout = setTimeout(bind(function() {  this.error_meassage.text(""); this.error_meassage.errorMessageTimeout = -1; }, this),2000);
            }
            ,this.window1);
        this.window1.proceedBtn = this.window1.find(".form_confirm_button");
        this.window1.proceedBtn.click(bind(this.setName, this));

        var inputs = this.window1.find(".form_input_field_sign");
        this.window1.input_fn = $(inputs[0]);
        this.window1.input_ln = $(inputs[1]);




		///////////////////
		
		
		this.bkImage = $(this.mainObject).find(".profile_background_img");
        this.setUpBk(this.bkImage);
        $(document).mouseup(bind(this.bkMouseUp, this));
        $(document).mousemove(bind(this.bkMouseMove, this));

		this.bkContainer = $(this.mainObject).find(".profile_background_cont");
		
		var a = null;
		
		//setup buttons
		this.timelineButton = $(this.mainObject).find(".profile_sub_timeline_0");
		this.timelineButton.click(bind(function() { this.detectState(""); },this));
		
		this.storiesButton = $(this.mainObject).find(".profile_sub_stories_0");
		this.storiesButton.click(bind(function() { this.detectState("stories"); },this));
		
		this.privateButton = $(this.mainObject).find(".profile_sub_private_0");
		this.privateButton.click(bind(function() { this.detectState("private"); },this));
		
		
		//set up states
		//timeline
		a = { 	N : 0,
				urlPrefix : "",
				show : bind(function()
				{
                    //WHP.stats.trackPageChange("/user/"+this.curUserId+"/");
					this.timelineCont.css({ display : 'block' });
					this.timelineObject.show(0);
				}, this),
				hide : bind(function()
				{
					this.timelineObject.hide();
					this.timelineCont.css({ display : 'none' });
				}, this),
                restore : bind(function()
                {
                    if (WHP.controller.removedList.length>0)
                    {
                        this.timelineObject.rebuildTimeline(WHP.controller.removedList, this.restoreParams);
                    }else{
                        this.timelineObject.restore();
                    }

                    this.timelineCont.css({ display : 'block' });
                }, this),
				cont : this.timelineCont,
				
				button : this.timelineButton,
				classPrefix : "profile_sub_timeline_"
			}
		this.states.push(a);
		
		//stories
		a = { 	N : 1,
				urlPrefix : "stories",
				show : bind(function()
				{
                    //WHP.stats.trackPageChange("/user/"+this.curUserId+"/stories/");
					this.storiesCont.css({ display : 'block' });
					this.storiesObject.show();
				}, this),
				hide : bind(function()
				{
					this.storiesObject.hide();
					this.storiesCont.css({ display : 'none' });
				}, this),
                restore : bind(function()
                {
                    if (WHP.controller.removedList.length>0)
                    {
                        this.storiesObject.show();
                    }else{
                        this.storiesObject.restore();
                    }

                    this.storiesCont.css({ display : 'block' });
                }, this),
				cont : this.storiesCont,
				
				button : this.storiesButton,
				classPrefix : "profile_sub_stories_"
			}
		this.states.push(a);
		
		//subscribers
		a = { 	N : 2,
				urlPrefix : "subscribers",
				show : bind(function()
				{
                    //WHP.stats.trackPageChange("/user/"+this.curUserId+"/subscribers/");
					this.subscribersCont.css({ display : 'block' });
					this.subscribersObject.show();
				}, this),
				hide : bind(function()
				{
					this.subscribersObject.hide();
					this.subscribersCont.css({ display : 'none' });
				}, this),
                restore : bind(function()
                {
                    this.subscribersObject.restore();
                    this.subscribersCont.css({ display : 'block' });
                }, this),
				cont : this.subscribersCont,
				
				button : null,
				classPrefix : null
			}
		this.states.push(a);
		
		//subscriptions
		a = { 	N : 3,
				urlPrefix : "subscriptions",
				show : bind(function()
				{
                    //WHP.stats.trackPageChange("/user/"+this.curUserId+"/subscriptions/");
					this.subscriptionsCont.css({ display : 'block' });

					this.subscriptionsObject.show();
                    this.newfacesObject.show();
				}, this),
				hide : bind(function()
				{
					this.subscriptionsObject.hide();
                    this.newfacesObject.hide();

					this.subscriptionsCont.css({ display : 'none' });
				}, this),
                restore : bind(function()
                {
                    this.subscriptionsCont.css({ display : 'block' });

                    this.subscriptionsObject.restore();
                    this.newfacesObject.restore();

                }, this),
				cont : this.subscriptionsCont,
				
				button : null,
				classPrefix : null
			}
		this.states.push(a);
		
		//private
		//subscriptions
		a = { 	N : 4,
				urlPrefix : "private",
				show : bind(function()
				{
                    //WHP.stats.trackPageChange("/user/"+this.curUserId+"/private/");
					this.privateCont.css({ display : 'block' });
					this.privateObject.show(0);
				}, this),
				hide : bind(function()
				{
					this.privateObject.hide();
					this.privateCont.css({ display : 'none' });
				}, this),

                restore : bind(function()
                {
                    this.privateCont.css({ display : 'block' });
                    if (WHP.controller.removedList.length>0)
                    {
                        log("AFTER REMOVE!!");
                        this.privateObject.show(0);
                    }else{
                        this.privateObject.restore();
                    }
                }, this),

				cont : this.privateCont,
				
				button : this.privateButton,
				classPrefix : "profile_sub_private_"
			}
		this.states.push(a);
		
		
		
		this.curState = 0;
		this.defaultState = 0;
		
		this.pointsHelper.init( this.mainObject );

        this.resetRestore();


        this.newFaces.parent = this;
        this.newFaces.init();

        this.popupWindow.parent = this;
        this.popupWindow.init();

		
		this.inited = true;
	},

    clickChangeName : function(e)
    {
        this.window1.css({display:"block"});
        WHP.main_fader.show();

        //positions
        var scrollTop = getScrollTop();


        if (browser.ie)
        {
            this.window1.css({ position : 'absolute' });
            this.window1.css({ top : (scrollTop + (WHP.screenH - this.window1.height())*0.5 )+'px', left : (WHP.screenWl-285)*0.5 +'px' });
        }else
            this.window1.css({ top : (WHP.screenH - this.window1.height())*0.5 +'px', left : (WHP.screenWl-285)*0.5 +'px' });

        this.window1.input_fn.val(WHP.auth.userObject.first_name);
        this.window1.input_ln.val(WHP.auth.userObject.last_name);
        //this.window1.setState1();
        //this.window1.page1.input_pass.focus();

        return cancelEvent(e);
    },

    setName :function(e)
    {
        var fn = this.window1.input_fn.val();
        var ln = this.window1.input_ln.val();

        if (fn.length==0)
        {
            this.window1.showErrMsg("Enter your first and last name");
            this.window1.input_fn.focus();
            return false;
        }

        if (ln.length==0)
        {
            this.window1.showErrMsg("Enter your first and last name");
            this.window1.input_ln.focus();
            return false;
        }


        $.ajax({
            url:WHP.netcalls.setNameCall,
            data : { r : Math.random(), first_name : fn, last_name : ln },
            timeout:WHP.netTimeOut,
            success:bind(this.onsetNameOk, this),
            error:bind(this.onsetNameFail, this)
        });

    },

    onsetNameOk : function(response)
    {
        this.window1.activeSet = false;
        var resp = getObjectJson(response);
        if (resp.error)
        {
            this.window1.showErrMsg("Something went wrong!");
            this.mail_input.focus();
            return false;
        }

        this.hideWindow1();
        WHP.controller.reloadPage();
    },

    onsetNameFail : function(e)
    {
        this.window1.activeSet = false;
        this.window1.showErrMsg("Something went wrong!");
    },



    hideWindow1 : function()
    {
        if (this.window1.css("display") == 'none')
            return false;

        log("hideWindow2");
        this.window1.css({display:"none"});
        WHP.main_fader.hide();
    },


    onSubscriptionsData : function(resp)
    {
        var respC = resp.followers;
        if (!respC)
            respC = resp.followings;

        this.subscriptionsCount = respC.total;
        this.setFollowersLabels();
    },

    onSubscribeData : function(resp)
    {
        var respC = resp.followers;
        if (!respC)
            respC = resp.followings;

        this.subscribersCount = respC.total;
        this.setFollowersLabels();
    },
	
	hideSubWindows : function ()
	{
		WHP.pages.profile.pointsHelper.hide();
	},

    bkMouseDown : function (e)
    {
        if (!this.bkMove.moving)
            return false;

        this.bkMove.drUgEnable = true;

        $('#status2').html(e.pageX +', '+ e.pageY);

        this.bkMove.start.x = e.pageX;
        this.bkMove.start.y = e.pageY;
        this.bkMove.bkStart = this.bkMove.bkPos;

        return cancelEvent(e);
    },


    bkMouseUp : function (e)
    {
        if (!this.bkMove.moving)
            return false;

        if (!this.active)
            return false;


        this.bkMove.drUgEnable = false;
    },
    bkMouseMove : function (e)
    {
        if (!this.bkMove.moving)
            return false;

        if (!this.active)
            return false;

        if (!this.bkMove.drUgEnable)
            return false;

        this.bkMove.cur.x = e.pageX;
        this.bkMove.cur.y = e.pageY;

        var mVec = { x : this.bkMove.cur.x-this.bkMove.start.x, y : this.bkMove.cur.y-this.bkMove.start.y};

        this.bkSetPos(this.bkMove.bkStart + 2*mVec.y);
    },



    cancelMove : function()
    {
        this.bkMove.moving = false;
        this.bkMove.drUgEnable = false;

        this.setBk();
    },

    setUpBk : function(_el)
    {
      _el.mousedown(bind(this.bkMouseDown, this));
    },

    applyMove : function()
    {
        var a = document.createElement("img");
        setClass(a, "profile_background_img");
        var parent = this.bkImage.parent();
        this.bkImage.remove();
        this.bkImage = $(a);
        this.setUpBk(this.bkImage);
        $(parent).append(a);

        this.bkMove.deactiveButton.css({ display : 'none' });
        this.bkMove.activeButton.css({ display : 'none' });
        this.bkMove.loadInd.css({ display : 'none' });
        this.bkMove.moveInd.css({ display : 'none' });
        this.bkMove.moving = false;
        this.bkMove.drUgEnable = false;
        this.bkImage.css({visibility : 'hidden'});

        this.bkContainer.css({ 'background-image' : 'url(/gui/loading_ani.gif?whp16)'});
        setClass(this.bkImage, "profile_background_img");


        $.ajax({
            url: WHP.netcalls.shiftBkCall ,
            data : { y : -this.bkMove.bkPos },
            timeout : WHP.netTimeOut,
            success: bind(this.applyCallback, this),
            error: bind(this.applyCallback, this)
        });
    },

    applyCallback : function(response)
    {
        var resp = getObjectJson(response);

        this.userObject.background['i1000x314'] = resp.background;
        this.setBk();
    },
    //1
    startMove : function()
    {
        if (!this.bk)
            return false;

        //this.bkMove.moving = true;
        this.bkMove.deactiveButton.css({ display : 'none' });
        this.bkMove.activeButton.css({ display : 'none' });

        this.bkMove.loadInd.css({ display : 'block' });
        this.bkMove.moveInd.css({ display : 'none' });


        setOnLoadIMG(this.bk['i1000x1000'], bind(this.imgLoaded, this));


    },

    bkSetPos : function(_y)
    {
        var _nY = Math.max( -(1000-314), Math.min(0,_y));
        this.bkMove.bkPos = _nY;
        this.bkImage.css({ top : _nY+'px'});
    },

    //2
    imgLoaded : function()
    {
        this.bkMove.moving = true;
        setClass(this.bkImage, "profile_background_img_move");
        this.bkImage.attr('src', this.bk['i1000x1000']).css({ visibility: 'visible', height : 1000+'px', width: 1000+'px'});
        this.bkSetPos(0);

        this.bkMove.deactiveButton.css({ display : 'none' });
        this.bkMove.activeButton.css({ display : 'block' });

        //this.profile_moveButton.css({ display : 'none' });
        this.bkMove.loadInd.css({ display : 'none' });
        this.bkMove.moveInd.css({ display : 'block' });
    },

	
	show: function (_q)
	{
		//_q - query string
		var q = _q;
		if (!q)
			q = "/";		
		var params = q.split("/");
		this.params = params;

        if (String(document.location).indexOf("/profile")>-1)
        {
            if (!WHP.auth.status)
            {
                WHP.controller.navigateTo("popular/");
                return false;
            }else{
                WHP.controller.navigateTo("user/"+WHP.auth.status.id);
            }
        }




        this.resetRestore();


		this.curUserId = WHP.auth.status.id;	
		this.timelineObject.controlUrl = WHP.netcalls.timelineCallUrl+"?user="+this.curUserId;
		this.storiesObject.controlUrl = WHP.netcalls.storiesUserCall+"?user="+this.curUserId;
		
		this.subscribersObject.controlUrl = WHP.netcalls.followersCall+"?user="+this.curUserId;
		this.subscriptionsObject.controlUrl = WHP.netcalls.followingsCall+"?user="+this.curUserId;

        this.newfacesObject.controlUrl = WHP.netcalls.newFacesCall;
		
		this.privateObject.controlUrl = WHP.netcalls.userPhotosCall+"?user="+this.curUserId+"&area=private";

        this.privateObject.urlPrefix = this.urlStr2+"/"+WHP.auth.status.id;
        this.timelineObject.prefix = this.urlStr2+"/"+WHP.auth.status.id;



        this.bkMove.drUgEnable = false;
        this.bkMove.bk_moving = false;

        this.bkMove.deactiveButton.css({ display : 'none' });
        this.bkMove.activeButton.css({ display : 'none' });

        this.bkMove.loadInd.css({ display : 'none' });
        this.bkMove.moveInd.css({ display : 'none' });
		

		this.getProfile();
	},


    onContentHeightChange : function(e)
    {

    },

    resetRestore : function()
    {
        this.restoreParams = {
            scrollpos : 0,
            setScroll : false
        };
    },

    //std for each module control functions
    restore: function (e)
    {
        //_q - query string
        var q = e;
        if (!q)
            q = "/";
        var params = q.split("/");
        this.params = params;



        if (this.bkMove.bk_moving)
        {
            this.setBk();
        }

        if (this.restoreParams.timelineRestoreResponse)
        {
            this.timelineObject.onData(this.restoreParams.timelineRestoreResponse,  this.timelineObject.startPage);
            this.restoreParams.timelineRestoreResponse = null;
        }

        this.restoreParams.setScroll = true;

        WHP.controller.showCanvas();

        var chStr = "";
        if (params.length>1)
            chStr = params[1];

        if (this.states[this.curState].urlPrefix != chStr)
        {
            this.detectState(chStr, true);
        }else{
            //restore prototypes
            this.states[this.curState].restore();
        }
    },


	hide: function (_q)
	{
        this.restoreParams.scrollpos = $(document).scrollTop();
        log("PROFILE HIDE = ["+this.restoreParams.scrollpos+"]");
        this.active = false;
		this.timelineObject.hide();

        this.subscribersObject.hide();
        this.subscriptionsObject.hide();
        this.newfacesObject.hide();
        this.storiesObject.hide();

        this.popupWindow.hide();
	},
	
	
	getProfile: function ()
	{		
		$.ajax({
			  url: WHP.netcalls.getProfileCall,
              data : { user : this.curUserId, r : Math.random() },
			  timeout : WHP.netTimeOut,
			  success: bind(this.onData, this),
			  error: bind(this.onError, this)
		});
	},
	
	
	onData : function (response, status, xhr)
	{
        if (!this.active)
            return false;

		window.scroll(0,0);
		var resp = getObjectJson(response);		
		if (resp.error)
		{
			log("WHP/pages/user : get picture error = ["+resp.error.code+"]");
			if (!WHP.errors.hasNetError(resp))
			{
				WHP.controller.showErrorPage();
			}
			return false;
		}	
		
		this.userObject = resp.user;
		this.timelineObject.userObject = this.userObject;
		
		
		this.newFaces.show();

		this.setProfile(resp);
		this.setTitle(resp);

        this.active = true;
		WHP.controller.showCanvas();
		
		var qStr = "";
		if (this.params.length>1)
			qStr = this.params[1];


        log("!!!!!!!!!!!!!!!!!!!!!!!!! = ["+qStr+"]");
		this.detectState(qStr);
		//this.timelineObject.show(0);
		//this.storiesObject.show(0);
	},
	
	
	onError : function (e)
	{
		log("WHP/pages/user: Error while loading actual data! : ["+e+"]");
	},	
	
	
	setProfile : function (resp)
	{
		if (resp.user.photo)
			ava = resp.user.photo['i106x106'];
		this.setAvatar(ava);	
				
		var a = $(this.mainObject).find( ".profile_name_label" );	
		a.text(resp.user.name);
        //a.text("MMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMM");
		
		this.follow = resp.user.follow;

		
	
		this.subscribersCount = resp.user.followers_count;
		this.subscriptionsCount = resp.user.followings_count;
		this.pointsCount = resp.user.points ;
		
		this.subscribersObject.setName("Subscribers");
		this.subscriptionsObject.setName("Subscriptions");
        this.newfacesObject.setName("New faces");

		
		this.bk = resp.user.background;
        this.setBk();
	
		this.setFollowersLabels();
		//points
		
		
		a = $(this.mainObject).find( ".profile_avatar_image" );
		var ava = null;
	},
	
	setBk : function ()
	{
		var _link = "http://"+WHP.domain+"/gui/profile_default_bk.jpg";
		if (this.bk)
		{
            _link = this.bk['i1000x314'];
            this.bkMove.deactiveButton.css({ display : 'block' });
            this.bkMove.activeButton.css({ display : 'none' });
		}else{
            this.bkMove.deactiveButton.css({ display : 'none' });
            this.bkMove.activeButton.css({ display : 'none' });
        }

        this.bkMove.loadInd.css({ display : 'none' });
        this.bkMove.moveInd.css({ display : 'none' });

        this.bkMove.moving = false;
        this.bkMove.drUgEnable = false;

        this.bkContainer.css({ 'background-image' : 'url(/gui/loading_ani.gif?whp16)'});
        setClass(this.bkImage, "profile_background_img");
        this.bkImage.css({  height : 314+'px', width: 1000+'px', top:0+'px'});
        setImageOnload(this.bkImage, _link, this.bkContainer );
	},
	
	
	setFollowersLabels : function ()
	{
		var lcds = $(this.mainObject).find(".profile_n_label");
		this.followersLCD = $(lcds[1]);
		this.followingsLCD = $(lcds[0]);
		this.pointsLCD = $(lcds[2]);
		
		//followers
		this.followersLCD.text(this.subscribersCount + " subscribers");
		if (this.subscribersCount==1)
			this.followersLCD.text(this.subscribersCount + " subscriber");
			
		//following
		this.followingsLCD.text(this.subscriptionsCount + " subscriptions");
		if (this.subscriptionsCount==1)
			this.followingsLCD.text(this.subscriptionsCount + " subscription");
			
		this.pointsLCD.text(this.pointsCount + " points");
		if (this.pointsCount==1)
			this.pointsLCD.text(this.pointsCount + " point");
	},
	
	
	setAvatar : function (_str)
	{
		if (!_str)
		{
			if (this.avatarPic)
			{
				$(this.avatarPic).remove();
				this.avatarPic = null;
			}
		}else{
			if (this.avatarPic)
			{
				$(this.avatarPic).remove();
				this.avatarPic = null;
			}
			
			var a  = $(this.mainObject).find( ".profile_avatar_image_cont" );	
			
			this.avatarPic = document.createElement("img");
			setClass(this.avatarPic, "profile_avatar_img");	
			this.avatarPic.src = _str;
			a.append(this.avatarPic);
		}
	},
	
	
	
	onSubscribeCallback : function (_a)
	{
        this.subscriptionsCount = this.subscriptionsCount+_a;
		this.setFollowersLabels();
	},
	
	onSubscriptionCallback : function (_a)
	{
		this.subscriptionsCount = this.subscriptionsCount+_a;
		this.setFollowersLabels();
	},


    onNewfacesCallback : function (obj)
    {
        if (obj.target.parent.curTotal == 0)
        {
            if (this.newFaces.active)
                this.popupWindow.hide();
        }


        if (!obj.follow)
        {
            this.subscriptionsObject.removeElement(obj.target.uid);
        }
        //WHP.resetH();
        //this.subscriptionsObject.addElement(_a);
    },


    onNewFacesData : function(resp)
    {
        if (this.newFaces.userL != resp.newfaces.total)
        {
            this.newFaces.showCallBack(resp);
            this.subscriptionsObject.refresh();
        }
        //WHP.resetH();
    },
	
	
	
	setTitle : function (resp)
	{
		this.title = resp.user.name;	 
		WHP.controller.setTitle(); 
	},
	
	detectState : function (q, _NotChangeLink)
	{
		var startState = this.curState;
		var newState = this.defaultState;
		for (var i=0; i<this.states.length; i++)
		{
			if (this.states[i].urlPrefix == q)
			{
				newState = i;
				break;
			}
		}

		//switch to
		this.curState = newState;
		for (var i=0; i<this.states.length; i++)
		{
			if (i == newState)
			{
				this.states[i].show();
				if (this.states[i].button)
					setClass(this.states[i].button,  this.states[i].classPrefix+"1");				
			}else{
				this.states[i].hide();
				if (this.states[i].button)
					setClass(this.states[i].button,  this.states[i].classPrefix+"0");
			}
		}

		if (startState != newState)
		{
			var stateStr = "";
			if (this.curState>-1)
			{
				if (this.states[this.curState].urlPrefix != "")
					stateStr  = this.states[this.curState].urlPrefix+"/";
			}
			var urla = this.urlStr2+"/"+WHP.auth.status.id+"/"+stateStr;
            if (!_NotChangeLink)
            {
			    setLink( "http://" + WHP.domain + "/" + urla);
            }
		}
        WHP.shares.hideAct2();
		//WHP.resetH();
	},

    moveButtons : function(_dY)
    {
        this.bkMove.buttonsCont.css({ top : _dY + 8 + 'px'});
    },
	
	
	
	pointsHelper : {
	
		inited : false,
		
		windCont : null,
		linkElem : null,
		
				
		//init function
		init: function (_el)
		{		
			this.linkElem = _el
			this.windCont = $(_el).find( ".points_window" ).get()[0];	
			this.inited = true;
		},
		
		show: function ()
		{
			this.windCont.style.display = "block";
			this.setPos();		
			//WHP.resetH();
		},


        shClick: function (_q)
        {
            if (this.windCont.style.display == 'none')
                this.show()
            else
                this.hide();
        },

		
		setPos: function ()
		{
			this.windCont.style.left = -(this.windCont.offsetWidth)*0.5 + 20 +'px';
			this.windCont.style.top = 38+'px';
		},

        clickButton: function (e)
        {
            if (this.windCont.style.display == "none")
            {
                //show
                this.show();
            }else{
                //hide
                this.hide();
            }
            return cancelEvent(e);
        },

		hide: function ()
		{
			this.windCont.style.display = "none";
		}



	},


    newFaces : {
        parent : null,
        mainObject : null,
        oneUser : false,
        userId : 0,
        userL : 0,

        active : false,

        init : function(){
            this.mainObject = $("#newfaces_slider_cont").clone();
            this.mainObject.removeAttr("id");

            this.mainObject.ava = this.mainObject.find(".timeline_header_avatar_img");
            this.mainObject.ava_cont = this.mainObject.find(".timeline_a_ava_holder");
            this.mainObject.text_label = this.mainObject.find(".newfaces_text");

            var buttons = this.mainObject.find(".profile_button_newfaces");

            this.mainObject.button_viewAll = $(buttons[1]);
            this.mainObject.button_viewAll.label = this.mainObject.button_viewAll.find(".profile_button_newfaces_label");
            this.mainObject.button_close = $(buttons[0]);
            this.mainObject.button_close.label = this.mainObject.button_close.find(".profile_button_newfaces_label");

            this.mainObject.button_close.click(bind(this.button2_click, this));
            this.mainObject.button_viewAll.click(bind(this.button1_click, this));
        },

        followResponse: function(response)
        {
            this.parent.popupWindow.hide();
        },


        button1_click : function(e)
        {
            if (this.oneUser)
            {
                var call = WHP.netcalls.followCall;
                WHP.opengraph.makeFolowAction(this.userId);
                $.ajax({
                    url: call,
                    data : { user : this.userId, r : Math.random() },
                    timeout : WHP.netTimeOut,
                    success: bind(this.followResponse, this),
                    error: bind(this.followError, this)
                });
            }else{
                this.parent.detectState("subscriptions");
                this.parent.popupWindow.hide();
            }
        },

        button2_click : function (e)
        {
            if (this.oneUser)
            {
                var call = WHP.netcalls.unfollowCall;
                $.ajax({
                    url: call,
                    data : { user : this.userId, r : Math.random() },
                    timeout : WHP.netTimeOut,
                    success: bind(this.followResponse, this),
                    error: bind(this.followError, this)
                });
            }else{
                this.hide();
            }
        },

        followError: function(e)
        {
            log("Follow error");
        },


        show : function () {

            this.getInfo();
            this.active = true;
        },

        hide : function () {
            this.parent.popupWindow.hide();
            this.active = false;
        },



        getInfo : function()
        {
            this.userL = 0;
            $.ajax({
                url: WHP.netcalls.newFacesCall ,
                data : { r : Math.random() },
                timeout : WHP.netTimeOut,
                success: bind(this.showCallBack, this),
                error: bind(this.showCallBackErr, this)
            });
        },

        showCallBack : function (response)
        {
            var resp = getObjectJson(response);
            if (resp.error)
            {
                log("WHP/pages/user : get picture error = ["+resp.error.code+"]");
                if (!WHP.errors.hasNetError(resp))
                {
                    WHP.controller.showErrorPage();
                }
                return false;
            }
            this.userL = resp.newfaces.total;

            if (resp.newfaces.total>0)
            {
               // this.mainObject.ava =
                //this.mainObject.ava_cont = this.mainObject.find(".timeline_a_ava_holder");

                if (resp.newfaces.list[0].photo)
                {
                    this.mainObject.ava.attr("src", resp.newfaces.list[0].photo['i106x106']);
                }else{
                    this.mainObject.ava.attr("src", "/gui/profile_no_ava49.jpg");
                }


                var str = "<a class='newfaces_text' style='top:0px;' href='"+WHP.links.getUserProfileLink(resp.newfaces.list[0].id)+"'><b>"+resp.newfaces.list[0].name+"</b></a>";
                this.oneUser = true;
                if (resp.newfaces.list.length>1)
                {
                    this.oneUser = false;
                    if (resp.newfaces.list.length== 2)
                    {
                        str = str +" and 1 other person";
                    }else{
                        str = str +" and "+(resp.newfaces.list.length-1)+" other people";
                    }
                }
                str = str + " joined WeHeartPics";

                if (this.oneUser)
                {
                    this.userId = resp.newfaces.list[0].id;
                    this.mainObject.button_close.label.text("Remove");
                    this.mainObject.button_viewAll.label.text("Ok");
                }else{
                    this.mainObject.button_close.label.text("Close");
                    this.mainObject.button_viewAll.label.text("View all");
                }

                this.mainObject.text_label.html(str);

                addIntelloLinks( this.mainObject.text_label );
                this.parent.popupWindow.setContentAfterHide(this.mainObject);
            }
        },

        showCallBackErr : function (response)
        {
            log("new faces fail");
        }
    },


    popupWindow : {
        parent : null,
        mainObject : null,
        timer : new Timer(1000/35, 9),
        cP : 0,
        p0 : 0,
        p1 : 1.0,
        contentH : 55,

        content : null,
        content2 : null,


        init : function()
        {
            this.timer.onTimerEvent = bind(this.timerMove, this);
            this.mainObject = $(this.parent.mainObject).find(".photobig_slider");
        },

        timerMove : function(e)
        {
            var A = e.currentCount/e.repeatCount;
            if (this.p0<this.p1)
            {
                var B = Math.pow( Math.sin(Math.PI*0.5*A), 0.18);
            }else{
                var B = Math.sin(Math.PI*0.5*A);
            }

            this.cP = (1-B)*this.p0 + B*this.p1;
            this.mainObject.css({ height : this.contentH*this.cP + 'px'});

            this.parent.moveButtons(this.contentH*this.cP);

            if (A == 1)
            {
                if (this.cP == 0)
                {
                    if (this.content2)
                    {
                        this.setContent(this.content2);
                    }
                }
            }
        },

        setContentAfterHide : function(_el)
        {
            if (this.cP!=0.0)
            {
                //
                this.content2 = _el;
                this.hide();
            }else{
                if (this.content)
                    this.content.detach();

                this.content = _el;
                this.mainObject.append(this.content);
                this.show();
            }
        },

        setContent : function(_el)
        {
            if (this.content)
                this.content.detach();

            this.content = _el;
            this.mainObject.append(this.content);

            if (this.content2)
            {
                this.show();
                this.content2 = null;
            }
        },

        show : function()
        {
            this.p0 = this.cP;
            this.p1 = 1.0;

            this.timer.reset();
            this.timer.start();
        },

        hide : function()
        {
            this.p0 = this.cP;
            this.p1 = 0.0;

            this.timer.reset();
            this.timer.start();
        }
    }
}



whp_feed_proto = function () { return {
	//controller parametres
	inited : false,
	
	
	//data loading parametres
	controlUrl : "",
	
	//url options
	urlPrefix : "",
	changeUrl : false,
	
	//canvas control
	controlCanvas : true,
	scrollCanvas : true,
    useGalleryPhoto : false,
	
	emptyElement : null,

    hidePaginOnNull : true,
	
	
	
	curOffset : 0,
	curTotal : 0,
	imageLimit : 30,
	images : [],
	
	//html elements
	mainCont : null,
	mainObject : null,
	photoContainer : null,
		
	pagingContainer : null,
	paginL : null,
	paginR : null,
	
	//template id/classes
	photoTemplate : null,
	
	//localvars	
	scrollTopBackup : 0,
	
	onLoadCall : null,
	
	show1 : false,
	
	curUrl : "",

    loadingBar : null,
	
			
	//init function
	init: function (_cont)
	{
		this.mainObject = $('#feed_template');
		this.mainObject = $(this.mainObject).clone();
		this.mainObject.removeAttr('id');
		
		
		this.emptyElement = $('#feed_empty_template_medium');
		this.emptyElement = this.emptyElement.clone();
		
		
		this.photoContainer = $(this.mainObject).find( ".feed_photo_box" );		
		this.pagingContainer = $(this.mainObject).find( ".feed_paging" );
		
		this.paginL = $(this.pagingContainer).find( ".std_paging_left" );
		this.paginL.click(bind(function () { this.getPage(-1); },this));
		this.paginR = $(this.pagingContainer).find( ".std_paging_right" );
		this.paginR.click(bind(function () { this.getPage(1); },this));
		
		
		this.photoTemplate = $("#feed_pageimage");
		this.photoTemplate = $(this.photoTemplate).clone();
		this.photoTemplate.removeAttr('id');
		
		this.mainCont = $(_cont);
		this.mainCont.append(this.mainObject);
		
		$(this.photoContainer).append(this.emptyElement);
		$(this.emptyElement).css({display : 'none' });


        this.loadingBar = $("#notifications_loading_tab").clone().removeAttr('id');

        this.loadingBar.css({ display : 'block', margin : 'auto', width: 50+'px'});



		this.inited = true;
	},

	saveScrollPos : function ()
	{
		this.scrollTopBackup = (document.all ? document.scrollTop : window.pageYOffset);		
	},
	
	restoreScrollPos : function ()
	{
		window.scroll(0,this.scrollTopBackup);		
	},
	
	//std for each module control functions
    restore : function()
    {


    },

	show: function (_off)
	{
		//clear canvas
		this.show1 = true;
		this.cleanUp(_off);
        this.photoContainer.append(this.loadingBar).css({ display : 'block'});
		this.loadPhotoPack();
		WHP.controller.setTitle();
	},
	
	hide: function()
	{
		
	},

    restore : function()
    {

    },
	
	cleanUp : function (_off)
	{
		this.clearCanvas();
		this.curOffset = _off;
		this.curTotal = _off;
	},
		
	
	//loads data function
	loadPhotoPack: function ()
	{
		//clear canvas
		this.clearCanvas();		
		var pageParam = parseInt(this.curOffset/this.imageLimit);
		if (pageParam==0)
			pageParam = ""
		else
			pageParam = pageParam +"/";
			
			
		if (this.changeUrl)
		{
			var urla = this.urlPrefix+"/"+pageParam;
			if (!this.show1)
				setLink( "http://" + WHP.domain + "/" + urla);
		}
		
		this.curUrl = this.controlUrl;
		var url = this.controlUrl;
		//donot duplicate? use 1 instance?
		
		$.ajax({
			  url: this.controlUrl,
			  timeout : WHP.netTimeOut,
			  data : { offset : this.curOffset, limit : this.imageLimit, r :  Math.random() },
			  success: bind(function (r,s,x){ var curl = url; this.onData(r,s,x, curl); }, this),
			  error: bind(this.onError, this)
			});
	},
	
	onData : function (response, status, xhr, url)
	{
		// is it the last call?
		if (this.curUrl != url)		
			return false;
		
		this.clearCanvas();		
		this.show1 = false;
		
			
		var resp = getObjectJson(response);	
		if (resp.error)
		{
			log("WHP/feed_prot : error while loading page data! Err =["+response+"]");
			if (!WHP.errors.hasNetError(resp))
			{
				WHP.controller.showErrorPage();
			}
			return false;
		}
		//generate new

		if (this.onLoadCall)
			this.onLoadCall(resp);
		
				
		var respCont = resp.photos;
		if (!respCont)
			respCont = resp.photobox;
		if (!respCont)
			respCont = resp.feed;
		
		this.curTotal = respCont.total;


        this.loadingBar.remove();
		for (var i=0; i<respCont.list.length; i++)
		{
			var obj = respCont.list[i];
			var element_div = this.newImage(obj);
            element_div.N = new Number(i);
			if (i % 3 == 2)
				element_div.css({ 'margin-right' : '0px' });
			//element_div.likesLCD.text( i+" "+(i % 3 == 2));
			$(this.photoContainer).append(element_div);
			this.images.push(element_div);	
		}	
		addIntelloLinks(this.photoContainer);	
		
		if (this.images.length==0)
		{
			$(this.photoContainer).append(this.emptyElement);
			$(this.emptyElement).css({display : 'block' });
		}else{
			$(this.emptyElement).css({display : 'none' });
		}
		
		if (this.controlCanvas)
			WHP.controller.showCanvas()
		else
			this.mainCont.css({ display : 'block' });
			
		if (this.scrollCanvas)
			window.scroll(0,0);
		
		this.checkPagingState();	
		//WHP.resetH();
	},

    getPhotoPage : function()
    {
        WHP.pages.photo.imagesList.setContentLink(this.response, this.parent.curOffset + this.N, this.parent.controlUrl);
    },

	newImage: function(resp)
	{
		//log("new image = ["+resp.like+"] ["+resp.photo_id+"] by ["+resp.user_name+"]");
		var element_div = this.photoTemplate.clone();
		element_div.image = element_div.find(".img_template_like_212_img");
		element_div.image_link = element_div.find(".timeline_a_ava_holder");
		element_div.image_cont = element_div.find(".img_template_like_212_img_cont");
		element_div.likesLCD = element_div.find(".img_template_like_212_img_label");
		element_div.likesLCD_cont = element_div.find(".img_template_like_212_img_label");
        element_div.parent = this;
        element_div.response = resp;
		
		element_div.like = resp.like;
		element_div.photo_id = resp.id;
		element_div.uid = resp.uid;

        if (resp.user)
		    element_div.user_name = resp.user.name;
		
		element_div.likesLCD.text( NformatMin( element_div.like ) );
		//if (element_div.like==0)
		{
			element_div.likesLCD_cont = element_div.find(".img_template_like_212_img_like");
			element_div.likesLCD_cont.css({ display : 'none' });
		}


        if (this.useGalleryPhoto)
        {
            element_div.image_link.click(bind(this.getPhotoPage, element_div));
        }
		element_div.image_link.attr('href', WHP.links.getPhotoLink( resp.id));


        setImageOnload(element_div.image, resp['i212x212'], element_div.image_cont);
		
		return element_div;
	},
	
	//error callback
	onError : function (response, status, xhr)
	{
		log("WHP/feed_prot/ : Error while loading actual data! Err = ["+response+"]");
		WHP.controller.showErrorPage();
	},	
	
	getPage : function (_a)
	{
		if (this.controlCanvas)
			WHP.controller.hideCanvas()
		else
			this.mainCont.css({ display : 'none' });
			
		
		if (_a>0)
			this.curOffset = this.curOffset+this.imageLimit
		else
			this.curOffset = this.curOffset-this.imageLimit;	
					
		this.loadPhotoPack();
	},	
	
	//clears photos container
	clearCanvas : function ()
	{
		while(this.images.length>0)
		{
			var a = this.images.pop();
			a.remove();
		}
        if (this.hidePaginOnNull)
		    this.pagingContainer.css({display : 'none'});

		$(this.paginR).addClass("hidden");
		$(this.paginL).addClass("hidden");
		$(this.emptyElement).css({display : 'none'});
	},
	
	//checks forward/backward state
	checkPagingState: function ()
	{
		

		
		if (this.curTotal <= this.imageLimit)
		{
            this.paginL.addClass("hidden");
            this.paginR.addClass("hidden");
            if (this.hidePaginOnNull)
                this.pagingContainer.css({ display : 'none'});
		}else{
            if (this.hidePaginOnNull)
                this.pagingContainer.css({ display : ''});
			if (this.curOffset==0)
				this.paginL.addClass("hidden");
			else
				this.paginL.removeClass("hidden");
			
			if (this.curOffset >= this.curTotal-this.imageLimit )
				this.paginR.addClass("hidden")
			else
				this.paginR.removeClass("hidden");
		}
	}
}
}




whp_window_proto = function () { return {
	mainCall : "",
	inited : false,
	
	mainCont : null,
	windCont : null,
	itemsCont : null,
	itemsCanvas : null,
	
	scrollBar : null, 
	scrollBarJQ : null,
	
	scrollEnabled : true,
	clearOnShow : true,
	
	onEndFunc : null,
	
	position : {
		x : 0,
		y : 0
	},
	scrollPos : {
		x : 0,
		y : 0
	},
	scrollParams : {
		scrollBarH : 0,
		scrollBarPos : 0,
		scrollBarTotalH : 0,
		
		canvasH : 0,
		windH : 0,
		dY : 0,
		curA : 0,
		p0 : 0,
		p1 : 0
	},
	mousePos : {
		x : 0,
		y : 0,
		dX : 0,
		dY : 0,
		dnX : 0,
		dnY : 0,
		
		startScrollY : 0,
		startOffsetY : 0
	},
	
	scrollsShoHideTimer : new Timer(1000/30, 8),
	scrollsShowHideDelayTimer : new Timer(600,1),
	
	scrollDefault : true,
	
	visible : false,
	
	
	scrollDown : false,
    scroller : null,
			
	//init function
	init: function (_cont)
	{		
		//this.scrollDefault = (browser.mac) && (!browser.firefox) && (!browser.opera);
		this.scrollDefault = false;
		this.windCont = id$('notifications_template');
		
		this.windCont = $(this.windCont).clone();
		this.windCont.removeAttr('id');
		this.windCont.click(function (e){ return cancelEvent(e); });
		
		this.itemsCont = $(this.windCont).find( ".window_prot_container" ).get()[0];	
		this.itemsCanvas = $(this.windCont).find( ".window_prot_canvas" ).get()[0];
		this.topArr = $(this.windCont).find( ".window_prot_box_arrow" ).get()[0];
		
		if (this.scrollDefault)
			this.itemsCont.style['overflow-y'] = 'scroll';
		
		this.scrollBar = $(this.windCont).find( ".scrolling_bar" ).get()[0];		
		this.scrollCont = $(this.windCont).find( ".scrolling_container" ).get()[0];


		
		//se
		var mousewheelevt = (/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel";	
		var elem = this.windCont.get()[0];
		if (this.scrollDefault)
			AddHandler(elem, mousewheelevt, bind(this.scrollWindowMac,this))
		else{
			setAlpha(this.scrollBar,0);
			AddHandler(elem, mousewheelevt, bind(this.scrollWindow,this));
			
			this.scrollBarJQ = $(this.scrollBar);
			this.scrollBarJQ.mousedown(bind(this.mouseDownEvent, this));
			this.scrollBarJQ.mouseup(bind(this.mouseUpEvent, this));
			this.scrollBarJQ.mouseMoveEvent = bind(this.mouseMoveEvent, this);
			//scrollbar.mousemove(bind(this.mouseMoveEvent, this));
		}
		
		this.mainCont = $(_cont);
		this.mainCont.append(this.windCont);
		
		//timers
		this.scrollsShoHideTimer.onTimerEvent = bind(this.showHideScrolls, this);
		this.scrollsShowHideDelayTimer.onTimerEvent = bind(this.showHideScrollsDelay, this);


        //this.scroller = new iScroll(this.itemsCont);

		this.inited = true;
	},
	
	mouseDownEvent : function (e)
	{
		this.scrollDown = true;
		WHP.menu.downListEvent(this.scrollBarJQ);
		
		this.mousePos.dnX = e.pageX;
		this.mousePos.dnY = e.pageY;		
		this.mousePos.x = e.pageX;
		this.mousePos.y = e.pageY;
		this.mousePos.dX = 0;
		this.mousePos.dY = 0;
		this.mousePos.startScrollY = this.scrollParams.scrollBarPos;
		this.mousePos.startOffsetY = this.scrollBarJQ.offset().top;
		
		this.showScrolls();
		this.scrollsShowHideDelayTimer.reset();
		
		
		return cancelEvent(e);
	},
	
	mouseUpEvent : function (e)
	{
		this.scrollDown = false;
		this.scrollsShowHideDelayTimer.reset();
		this.scrollsShowHideDelayTimer.start();
		return cancelEvent(e);
	},
	
	mouseMoveEvent : function (newPos)
	{
		var newX = newPos.x;
		var newY = newPos.y;
		if (this.scrollDown)
		{
			//var newX = e.pageX;
			//var newY = e.pageY;
			this.mousePos.x = newX;
			this.mousePos.y = newY;
			
			this.mousePos.dX = this.mousePos.x - this.mousePos.dnX;
			this.mousePos.dY = this.mousePos.y - this.mousePos.dnY;
			
			var fY = this.mousePos.startScrollY + this.mousePos.dY;
			fY = Math.max(0, fY);
			fY = Math.min(this.scrollParams.scrollBarTotalH - this.scrollParams.scrollBarH, fY);
			
			var normolizedP = fY/(this.scrollParams.scrollBarTotalH - this.scrollParams.scrollBarH);
			this.scrollWindowTo(-normolizedP);
			
			if ( Math.abs(-normolizedP+1) < 50/this.scrollParams.canvasH )
			{
				log("LOAD!!!");
				if (this.onEndFunc)
					this.onEndFunc();
			}
		}
	},
	
	showScrolls : function (e)
	{
		if (this.scrollParams.p1!=1)
		{
			this.scrollParams.p0 = this.scrollParams.curA;
			this.scrollParams.p1 = 1;
			this.scrollsShoHideTimer.reset();
			this.scrollsShoHideTimer.start();
		}
		
		if (this.scrollsShowHideDelayTimer.active)
		{
			this.scrollsShowHideDelayTimer.reset();
			this.scrollsShowHideDelayTimer.start();
		}
	},
	
	hideScrolls : function (e)
	{
		if (this.scrollParams.curA != 0)
		{
			this.scrollParams.p0 = this.scrollParams.curA;
			this.scrollParams.p1 = 0;
			this.scrollsShoHideTimer.reset();
			this.scrollsShoHideTimer.start();
		}
	},
	
	showHideScrolls : function (e)
	{
		var A = e.currentCount/e.repeatCount;
		this.scrollParams.curA = (1-A)*this.scrollParams.p0 + A*this.scrollParams.p1;
		setAlpha(this.scrollBar, this.scrollParams.curA);
	},
	
	showHideScrollsDelay : function (e)
	{
		this.hideScrolls();		
	},
	

	show: function ()
	{
		if (this.clearOnShow)
			this.clearCanvas();
		this.windCont.css({ display : 'block'});
		
		this.scrollEnabled = true;
		this.scrollWindowTo(0);
		this.setScrollEn(false);
		this.visible = true;
        //this.scroller.refresh();
	},
	hide: function ()
	{
		this.windCont.css({ display : 'none'});
		this.visible = false;
	},
	
	
	setPos: function (_x, _y)
	{
		this.position.x = _x;
		this.position.y = _y;
		
		var sizeX = this.windCont.width();
		
		this.windCont.css({ left : _x - sizeX*0.5+'px', top : _y+16+'px'});
	},
	
	
	setSize: function (_w, _h)
	{	
		this.windCont.css({ width : _w+'px', height : _h+'px'});
		this.topArr.style.left = (_w-34)*0.5 + 'px';	
		
		this.setPos(this.position.x, this.position.y);
	},
	
	setH: function(_h)
	{
		this.windCont.css({ height : _h+'px'});		
	},
	
	setW: function(_w)
	{
		this.windCont.css({ width : _w+'px'});	
		this.topArr.style.left = (_w-34)*0.5 + 'px';		
	},
	
	setScrollEn : function (_enable)
	{
		this.scrollEnabled = _enable;
		if (this.scrollEnabled)
		{
			if (!this.scrollDefault)
				this.scrollCont.style.display = "block";
		}else{
			this.scrollCont.style.display = "none";
		}
	},
	
	
	scrollWindow: function(e)
	{
		
		if (this.scrollEnabled)
		{
			var evt=window.event || e //equalize event object
			var delta=evt.detail? evt.detail*(-120) : evt.wheelDelta;
			
			if (browser.firefox || browser.opera)
				delta = delta/10;
			
			
			var windH = this.windCont.height();
			var canvasH = this.itemsCanvas.offsetHeight;	
			delta = delta*0.5/canvasH;
			var pos = Math.min(this.itemsCanvas.offsetTop/Math.max(1, (canvasH-windH)),0);
			var fPos = pos + delta;
			
			
			this.scrollWindowTo(fPos);
			
			if ( Math.abs(fPos+1) < 50/canvasH)
			{
				if (this.onEndFunc)
					this.onEndFunc();
			}
			this.showScrolls();
			this.scrollsShowHideDelayTimer.reset();
			this.scrollsShowHideDelayTimer.start();
		}
		return cancelEvent(e);
	},
	
	scrollWindowMac: function(e)
	{
		
		if (this.scrollEnabled)
		{
			var evt=window.event || e //equalize event object
			var delta=evt.detail? evt.detail*(-120) : evt.wheelDelta;
			
			if (browser.firefox || browser.opera)
				delta = delta/10;
			
			
			var windH = this.windCont.height();
			var canvasH = this.itemsCanvas.offsetHeight;	
			delta = delta*0.5/canvasH;
			var pos = Math.max(this.itemsCont.scrollTop/Math.max(1, (canvasH-windH)),0);
			var fPos = pos - delta;
			fPos = Math.min(1, fPos);
			
			if ( Math.abs(fPos-1) < 50/canvasH)
			{
				if (this.onEndFunc)
					this.onEndFunc();
				if ( Math.abs(fPos-1) < 1/canvasH)
				{
					this.itemsCont.scrollTop = canvasH;
					return cancelEvent(e);
				}
			}
		}else
			return cancelEvent(e);
	},
	
	scrollWindowTo: function(_pos)
	{
		if (this.scrollEnabled)
		{
			var fPos = Math.min(0, _pos);
			fPos = Math.max(-1, fPos);	
			var canvasH = this.itemsCanvas.offsetHeight;	
			var windH = this.windCont.height();
			
			
			if (browser.ie)
				var stepH = 0
			else
				var stepH = 0;
			var newH = Math.min((windH-stepH)/canvasH*(windH-stepH), (windH-stepH));
			newH = Math.max(14, newH);

            //log("["+fPos+"] ["+windH+"] ["+stepH+"] ["+ newH+"]");
			var posS = -fPos*((windH-stepH) - newH);
			this.scrollBar.style.height = parseInt(newH)+'px';
			this.scrollBar.style.top = parseInt(posS)+'px';
			
			
			
			var topPos = 0;
			
			if (!this.scrollDefault)
			{
				topPos = -fPos*Math.max(0, (canvasH-windH));
				this.itemsCanvas.style.top = -topPos + 'px';
			}else{
				topPos = -fPos*Math.max(0, (canvasH-windH));
				this.itemsCont.scrollTop = topPos;
			}
			
			this.scrollPos.x = 0
			this.scrollPos.y = fPos;

			this.calculateScrollParams();
		}
	},
	
	calculateScrollParams : function()
	{
		this.scrollParams.canvasH = $(this.itemsCanvas).height();
		this.scrollParams.windH = this.windCont.height();
		
		var pos = 0;
		if (!this.scrollDefault)
		{
			pos = parseInt(this.itemsCanvas.style.top);
		}else{
			pos = parseInt(this.itemsCont.scrollTop);
		}
		this.scrollParams.dY = pos;
		
		var windH = this.scrollParams.windH;
		windH = Math.min(windH/this.scrollParams.canvasH*windH, windH);
		windH = Math.max(14, windH);
		this.scrollParams.scrollBarH = windH;
		this.scrollParams.scrollBarPos = parseInt(this.scrollBar.style.top);
		this.scrollParams.scrollBarTotalH = this.scrollParams.windH;

		var lastH = this.mousePos.dnY - this.mousePos.startOffsetY ;
		if (lastH>this.scrollParams.scrollBarH)
		{
			log("outOfScroll");
		}
	},
	
	setScrollBar: function()
	{
        var canvasH = $(this.itemsCanvas).height();
        var windH = this.windCont.height();
        var stepH = 0;


		var pos = Math.max(this.itemsCont.scrollTop/Math.max(1, (canvasH-windH)),0);
		var fPos = Math.min(1, pos);
		fPos = Math.max(0, fPos);


		var newH = Math.min((windH-stepH)/canvasH*(windH-stepH), (windH-stepH));
		newH = Math.max(14, newH);
			
		var posS = -fPos*((windH-stepH) - newH);
		this.scrollBar.style.height = parseInt(newH)+'px';
		this.scrollBar.style.top = parseInt(posS)+'px';
	},
	
	clearCanvas : function (e)
	{
		//clearcanvas
		while (this.itemsCanvas.hasChildNodes()) {
			this.itemsCanvas.removeChild(this.itemsCanvas.lastChild);
		}
	}	
}
}



whp_timeline_proto = function () { return {
	//controller parametres
	inited : false,
	active : false,
	
	
	//data loading parametres
	controlUrl : "",
	prefix : "",

    parent : null,
	

	lasttimeshtamp : 0,
	curOffset : 0,
	curTotal : 0,
	lastTotal : 0,
	curNew : 0,
	elementsLimit : 30,
    pagesN : 0,

	pages : [],
	curPage : null,
	startPage : null,

	loading : false,
	actMargin : 120,
	step_top : 20,
	step_bottom : 100,
	startY : 0,
	lastMargin : 0,



	//templates
    loadingBar : null,


    templatePhoto : null,
	templateStory : null,
	templateLike : null,
	templateFollow : null,


	templateLastvisit: null,
	lastVisitSetted : false,

	templateLikeSmall : null,
	templateFollowSmall : null,

	notifiesObject : null,

	templatePage : null,

	//html elements
	mainCont : null,
	mainObject : null,
	mainCanvas : null,
	clocksInd : null,

	userObject : null,

	//template id/classes
	templateLayout : "template_timeline",
	showEvents : true,
	controlCanvas : true,
	lastposRelated : true,
	displayLastVisit : true,
    showLoadingOnstart : false,

	controlUrl : "",
	initLoad : false,

    onErrorEvent : null,

    blocks_canvas : null,
    emptyTemplate : null,
    emptyTemplate2 : null,

    curTLcall : 0,
    jqxhr : null,

    usePosRecalAfterRebuild : false,
    showEmpty : false,



    restoreParams : null,

	//init function
	init: function (_cont)
	{
		this.mainObject = id$('timeline_template');
		this.mainObject = $(this.mainObject).clone();
		this.mainObject.removeAttr('id');
		this.mainObject.css({display : 'none'});

		this.blocks_canvas = $(this.mainObject).find(".blocks_canvas");
		//templates
		this.templatePhoto = $('#timeline_template_photo').clone();
		this.templatePhoto.removeAttr('id');

		this.templateStory = $('#timeline_template_story').clone();
		this.templateStory.removeAttr('id');

		this.templateLastvisit = $('#timeline_template_lastvisit').clone();
		this.templateLastvisit.removeAttr('id');

		this.templateLike = $('#timeline_template_like').clone();
		this.templateLike.removeAttr('id');


		this.templateLike.removeAttr('id');

		this.templateFollow = $('#timeline_template_follow').clone();
		this.templateFollow.removeAttr('id');

		this.templateLikeSmall = $('#timeline_template_like_elem').clone();
		this.templateLikeSmall.removeAttr('id');

		this.templateFollowSmall = $('#timeline_template_follow_elem').clone();
		this.templateFollowSmall.removeAttr('id');


		this.templatePage = $('#timeline_page_template').clone();
		this.templatePage.removeAttr('id');


        this.emptyTemplate = $("#timeline_empty_template").clone();
        this.emptyTemplate.removeAttr('id');

        this.emptyTemplate2 = $("#feed_empty_template_medium").clone();
        this.emptyTemplate2.removeAttr('id');


        this.setUpemptyElement(this.emptyTemplate);

		//objects
		this.notifiesObject = $('#timeline_template_new_notif').clone();
		this.notifiesObject.removeAttr('id');

		this.clocksInd = $(this.mainObject).find( ".timeline_clocks" );
		this.HasJoined = $(this.mainObject).find( ".timeline_join" );

		this.mainCanvas = $(this.mainObject).find( ".timeline_main_container" );

		this.mainCont = $(_cont);
		this.mainCont.append(this.mainObject);



        this.loadingBar = $("#notifications_loading_tab").clone().removeAttr('id');
        this.loadingBar.css({ display : 'block', margin : 'auto', width: 50+'px'});





		//add scroll event for end check
		//var mousewheelevt = (/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel";

		AddHandler(window, "scroll", bind(this.scrollEvent,this));

		this.inited = true;
	},


    setUpemptyElement : function(_elem)
    {
        _elem.defText = "Your e-mail address...";
        _elem.input = _elem.find(".timeline_empty_enter");
        _elem.input.val(_elem.defText);
        _elem.inputs = _elem.find(".timeline_empty_inputs");
        _elem.outputs = _elem.find(".timeline_empty_inputs");
        _elem.parent = this;


        _elem.formButton = _elem.find(".timeline_empty_notify_0");
        if (_elem.formButton.length == 0)
            _elem.formButton = _elem.find(".timeline_empty_notify_1");

        _elem.activeSend = false;

        _elem.input.focus(bind(this.onFocus, _elem));
        _elem.input.blur(bind(this.onBlur, _elem));
        _elem.input.keyup(bind(this.checkInput, _elem));

        _elem.formButton.click(bind(this.sendRequest, _elem));

        setClass(_elem.formButton, "timeline_empty_notify_0");


        _elem.downloadButtonT = _elem.find(".timeline_empty_download_iphone");

        if (this.showEvents)
        {
            _elem.downloadButtonT.click(function() { WHP.stats.trackDownload("DOWNLOAD_TIMELINE_MAIN_EMPTY") });
        }else{
            _elem.downloadButtonT.click(function() { WHP.stats.trackDownload("DOWNLOAD_TIMELINE_USER_EMPTY") });
        }
    },

    sendRequest : function(e)
    {
        if (this.activeSend)
            return false;

        if (!validateEmail(this.input.val()))
            return false;

        //http://weheartpics.com/api/promo/?email=rtbwerbrt%40wrerver.rr


        $.ajax({
            url:WHP.netcalls.promoCall,
            data : { r : Math.random(), email :  this.input.val() },
            timeout:WHP.netTimeOut,
            success:bind(this.parent.promoOk, this),
            error:bind(this.parent.promoFail, this)
        });
    },

    promoOk : function(e)
    {
       this.inputs.css({display : 'none'});
       setClass(this.outputs, "timeline_empty_output");
       this.outputs.css({display : 'block' }).html("We will email you when<br/>it is ready. See you soon!");
        this.activeSend = false;
    },

    promoFail : function (e)
    {
        this.inputs.css({display : 'block'});
        setClass(this.outputs, "timeline_empty_output_fail");
        this.outputs.css({display : 'block' }).html("Failed! Please, try again!");
        this.activeSend = false;
    },



    checkInput : function(e)
    {
        if (validateEmail(this.input.val()))
        {
            setClass(this.formButton, "timeline_empty_notify_1");
        }else{
            setClass(this.formButton, "timeline_empty_notify_0");
        }
    },


    onFocus : function(e)
    {
        if (this.input.val() == this.defText)
            this.input.val("");
    },

    onBlur : function(e)
    {
        if (this.input.val() == "")
            this.input.val(this.defText);
    },

    restore : function()
    {
        this.active = true;

        if (this.parent.restoreParams.setScroll)
        {
            setTimeout(bind(function() {
                if (this.restoreParams.setScroll)
                {
                    window.scrollTo(0,this.restoreParams.scrollpos);
                    WHP.menu.setShadow(this.restoreParams.scrollpos);
                    this.restoreParams.setScroll = false;
                }
            }, this.parent), 100);
        }
    },

	show: function(_offset)
	{
        this.curTLcall++;
        this.active = true;
		this.curOffset = _offset;
		this.curTotal = 0;
		this.curNew = 0;
		this.lasttimeshtamp = 0;
        this.pagesN = 0;

		this.startY = 0;
		this.lastMargin = 0;
		this.clearCanvas();
		this.initLoad = true;

        if (this.jqxhr)
            this.jqxhr.abort();

        this.loading = false;
        this.jqxhr = null;

		this.clocksInd.css({ display : 'none'});
		this.HasJoined.css({ display : 'none'});



		this.addNewPage();


        if (this.showLoadingOnstart)
        {
            this.startPage.mainCanvas.append(this.loadingBar).css({ display : 'block'});
        }

		this.loadElements();
	},

	hide: function()
	{
        log("TRACK TL = ["+this.active+"]");
        if (!this.active)
            return false;
		this.active = false;



        WHP.stats.trackTimeline(this.showEvents, this.pagesN);
	},

	loadElements: function()
	{
		if (this.controlUrl == "")
			return false;

		if (this.loading)
			return false;

		if ((this.curOffset >= this.curTotal) && (this.curOffset!=0))
			return false;

		if (!this.initLoad && (this.curTotal==0))
			return false;

		if (this.initLoad)
            WHP.controller.scrollToPos(0, 0);

		if (this.mainObject.css('display') != 'block')
			this.mainObject.css({display : 'block'});



        this.pagesN++;
		this.loading = true;
		var canvas = this.startPage;
        var curCall = new Number(this.curTLcall);
		this.jqxhr = $.ajax({
			  url: this.controlUrl,
			  timeout : WHP.netTimeOut,
			  data : { offset : this.curOffset, limit : this.elementsLimit, r : Math.random() },
			  success: bind(function(resp) { this.onData(resp, canvas, curCall); } , this),
			  error: bind(this.onError, this)
			});
	},

	onData: function(response, canvas, _nCall)
	{
        if (this.curTLcall != _nCall)
        {
            log("WRONG TIMELINE CALL! = ["+this.curTLcall+"] ["+_nCall+"]");
            return false;
        }


		this.loading = false;
        var resp = getObjectJson(response);

        if (!this.active)
        {
            log("set timelineRestoreResponse!") ;
            if (this.parent)
            if (this.parent.restoreParams)
                this.parent.restoreParams.timelineRestoreResponse = resp;

            log("parent = ["+this.parent+"] ["+this.parent.restoreParams+"] ["+this.parent.restoreParams.timelineRestoreResponse+"]");
            log("timelineRestoreResponse = ["+this.parent.restoreParams.timelineRestoreResponse+"]");
            return false;
        }


		if (resp.error)
		{
			log("WHP/timeline_prot : error while loading page data! Err =["+response+"]");
			if (!WHP.errors.hasNetError(resp))
			{
                if (this.onErrorEvent)
                {
                    var e = { error : 'DATA_ERROR' };
                    this.onErrorEvent(e);
                }
				//WHP.controller.showErrorPage();
			}
			return false;
		}




        if (this.showLoadingOnstart)
            this.loadingBar.detach();



		if (this.controlCanvas)
            WHP.controller.showCanvas();



		if (this.curOffset == 0)
		{
			//check is it ok?
			if (!resp.feed)
				return false;

			this.curTotal = resp.feed.total;
            this.lastVisitSetted = false;

			//last total
			if (this.lastposRelated)
			{
				var cookiename = "tl_lstt_"+this.prefix;
				var last = getCookie( cookiename );
				if (last!=null)
				{
					this.lastTotal = parseInt(last);
				}else{
					this.lastTotal = this.curTotal;
				}
				//this.lastTotal--;
				delCookie(cookiename);
				setCookieMin(cookiename,this.lastTotal,24*60);
			}else{
				this.lastTotal = this.curTotal;
			}


            if (this.curTotal == 0)
            //if (true)
            {
                setClass(this.mainObject,"blocks_canvas_empty");
                if (this.showEmpty)
                {
                    WHP.stats.trackEmptyTimeline(this.showEvents);
                    this.curPage.mainCanvas.append(this.emptyTemplate);
                }else{
                    this.curPage.mainCanvas.append(this.emptyTemplate2);
                }


                WHP.controller.scrollToPos(0, 0);
                this.clocksInd.css({ display : 'none'});
                this.initLoad = false;
                return false;
            }else{
                setClass(this.mainObject,"blocks_canvas");
                this.emptyTemplate.detach();
                this.emptyTemplate2.detach();
            }



			if (this.showEvents)
			{
				if (Math.abs(this.curTotal-this.lastTotal) % 2 == 0)
				{
					this.notifiesObject.addClass("timeline_float_right");
				}else{
					this.notifiesObject.addClass("timeline_float_left");
				}
				this.curPage.mainCanvas.append(this.notifiesObject);
			}


			this.curNew = resp.feed.newcount;
			this.lasttimeshtamp = resp.feed.last_visit_timestamp*1000;
			if (this.showEvents)
			{
				var lcd = this.notifiesObject.find(".events_number_cont");
				lcd.empty();
				var nGlyphs = printNotify19(this.curNew,lcd);

				var timeShtampLCDblock = this.notifiesObject.find(".events_n_container");
                var comment = this.notifiesObject.find(".events_text_container");

				var ts = 24;
				//timeShtampLCDblock.css({left : (3-nGlyphs+1)*ts + 'px'});
                timeShtampLCDblock.css({left : 13 + 'px'});
                comment.css({ left : 79 + (nGlyphs-2)*20 +'px'})
                //100px



				var str =  "New events since your last visit <br/>";
				str = str + getDateDelt(this.lasttimeshtamp)+" ago";
				comment.html(str);
			}
		}else{
            if (this.curTotal > resp.feed.total)
            {
                log("Recall width offset = ["+(this.curTotal-resp.feed.total)+"]");
                this.curOffset = this.curOffset - (this.curTotal-resp.feed.total);


                log("Get lastTotal = ["+this.lastTotal+"]");
                this.lastTotal = Math.max(0, this.lastTotal - ((this.curTotal-resp.feed.total) % 2));
                log("Set lastTotal = ["+this.lastTotal+"]");
                //delCookie(cookiename);
                //setCookieMin(cookiename,this.lastTotal,24*60);

                this.curTotal = resp.feed.total;
                this.loadElements();
                return false;
            }
        }

        var lastTimeshtamp = 0;
        if (this.pages[0].elements.length>0)
            lastTimeshtamp = this.pages[0].elements[this.pages[0].elements.length-1].timeshtamp;


        var listAdded = 0;
		for (var i=0; i<resp.feed.list.length; i++)
        {
            //this.addBlock(resp.feed.list[i], canvas);
            if (true)
            {
                if (lastTimeshtamp>0)
                {
                    if (resp.feed.list[i].timestamp*1000 < lastTimeshtamp)
                    {
                        listAdded++;
                        this.addBlock(resp.feed.list[i], canvas);
                    }
                }else{
                    listAdded++;
                    this.addBlock(resp.feed.list[i], canvas);
                }
            }
        }
        log("COUNT = [ "+listAdded+" / "+resp.feed.list.length+" ]");

		if (this.initLoad)
            WHP.controller.scrollToPos(0, 0);

		this.curOffset = this.curOffset + resp.feed.list.length;


		if (this.curOffset >= this.curTotal)
		{
			this.clocksInd.css({ display : 'none'});
			this.HasJoined.css({ display : 'block'});
			var label = this.HasJoined.find(".timeline_joined_template_label");

            //user name in timeline
			var userName = "";
			if (this.userObject)
                userName = this.userObject.name
            else
                if (WHP.auth.userObject)
                    userName = WHP.auth.userObject.name;

			var textL = userName+" joined WeHeartPics";
			label.html(textL);
			//end
		}else
			this.clocksInd.css({ display : 'block'});


		//log(response);
        this.initLoad = false;
	},


	addBlock : function( _resp, _canvas)
	{
		var b = null;

		if (this.displayLastVisit)
		if ((this.lasttimeshtamp>_resp.timestamp*1000) && (!this.lastVisitSetted))
		{
			if (_canvas.elements.length>0)
			{
				b = this.fillLastVisit();
				_canvas.mainCanvas.append(b);
			}
			this.lastVisitSetted = true;
		}

		if (_resp.type == "PHOTO")
		{
			b = this.createPhoto(_resp);
		}else if (_resp.type == "STORY")
		{
			b = this.createStory(_resp);
		}else if (_resp.type == "LIKE")
		{
			b = this.createLike(_resp);
		}else if (_resp.type == "FOLLOW")
		{
			b = this.createFollow(_resp);
		}else{
			log("WHP/timeline_prot : undeclarated type of element = ["+_resp.type+"]");
			return false;
		}

		this.appendBlock(b, _canvas);
	},

	addNewPage : function()
	{
		var newPage = this.templatePage.clone();
		newPage.mainCanvas = newPage.find(".timeline_page_cont");
		//setClass(newPage, "timeline_main_block");

		//vars
		newPage.elements = [];
		newPage.startY = 0;
		newPage.actMargin = this.actMargin;
		newPage.lastMargin = 0;


		if (this.pages.length == 0)
		{
			this.mainCanvas.append(newPage);
			this.startPage = newPage;
		}else{
			newPage.insertBefore(this.curPage);
			newPage.showSepLine();
		}

		this.pages.push(newPage);
		this.curPage = newPage;
	},

	showSepLine : function()
	{
		this.pageSeparator.css({display : 'block'});
		//this.css({'margin-top' : 16+'px'});
	},

	appendBlock: function(_b,_canvas)
	{
		var prevYend = 0;
		if (_canvas.elements.length>0)
		{
			var pos =_canvas.elements[_canvas.elements.length-1].position();
			prevYend = pos.top;
		}


		if ( (Math.abs(this.curTotal-this.lastTotal) - _canvas.elements.length) % 2 == 0)
		{
			_b.addClass("timeline_float_left");

			setFCK_FF_BKx(_b.find(".timeline_v_plate"), -20);
		}else{
			_b.addClass("timeline_float_right");

			setFCK_FF_BKx(_b.find(".timeline_v_plate"), 0);
		}

		_canvas.mainCanvas.append(_b);

		var posC = _b.position();


		if (_canvas.elements.length == 0)
		{
			_canvas.startY = posC.top;
			var step = _canvas.actMargin;
		}else{
			var step = posC.top - prevYend - _canvas.lastMargin;
		}

		var marginH = 0;
		if (step < _canvas.actMargin)
		{
			marginH = Math.max(_canvas.actMargin - step,0);
			_b.css({ 'margin-top' : marginH+ 'px'});
		}
        _b.positionTL = posC.top + marginH;

		_canvas.lastMargin = marginH;

		    _canvas.elements.push(_b);


		//line continue
		//var h = posC.top-this.startY+_b.height() + this.step_bottom + this.step_top + marginH;
		//this.lineObject.css({ height :  h + 'px', top : -this.step_top + 'px' });
	},

	fillLastVisit: function()
	{
		var a = this.templateLastvisit;
		a.timeShtampLCD = a.find(".timeline_lastvisit_label");
		a.timeShtampLCD.text("Your last visit was "+getDateDelt(this.lasttimeshtamp)+" ago");
		a.timeshtamp = this.lasttimeshtamp;
		return a;
	},

	createPhoto: function(_resp)
	{

		var user = _resp.user;
		if ((this.userObject) && (!user))
			user = this.userObject;

		var a = this.templatePhoto.clone();
		setFCK_FF_BKy(a.find(".timeline_v_plate"), 0);

        a.eType = "photo";
		a.parent = this;
		a.timeshtamp = _resp.timestamp*1000;
		a.uid = _resp.photo.user.id;
        a.caption = a.find(".timeline_caption");
        a.captionText = a.find(".timeline_caption_text");
        if (_resp.photo.caption)
        {
            a.captionText.text(_resp.photo.caption);
        }else{
            a.caption.css({ display : 'none'});
        }


		//set time
		a.timeShtampLCD = a.find(".timeline_timeshtamp");
		a.timeShtampLCD.text(getTimeFormatedTl(_resp.timestamp*1000));


		a.likesCount = _resp.photo.like;
		a.commentsCount = _resp.photo.comments_count;
		a.wasVote = _resp.photo.wasvote;
		a.photo_id = _resp.photo.id;


		//title
		a.titleLCD = $(a).find( ".timeline_header_text_cont" );
		var storyName = _resp.photo.story;

		if (typeof(storyName) == 'undefined')
		{
			storyName = "Draft";
			storyLink = WHP.links.getUserProfileLink(user.id)+"drafts/";
		}else{
			storyLink = WHP.links.getScenarioLink(storyName.id);
            if (storyName.type=="UNSORTED")
            {
                storyName = storyName.storyset.name;
            }else if (storyName.type=="TIMELINE")
            {
                storyName = "Snapshot";
            }else{
                storyName = storyName.name;
            }
		}

        if (_resp.photo.story.type=="TIMELINE")
        {
            storyName = "<span class='tl_theme_text_na' style='font-size:16px;font-weight:bold;'>"+storyName+"</span><br/>";
        }else{
            storyName = getTrimmedTextToSize(storyName,20,279,true);
            storyName = "<a class='tl_theme_text' style='font-size:16px;font-weight:bold;' href='"+storyLink+"'>"+storyName+"</a><br/>";

        }

        storyName = storyName + "by <a class='feed_author_name' style='font-size:16px' href='"+WHP.links.getUserProfileLink(user.id)+"' >"+user.name+"</a>";
		a.titleLCD.html(storyName);

		//avatar image
		a.avatarLCD = $(a).find( ".timeline_header_avatar_img" );
        if (user.photo)
        {
            $(a).find( ".timeline_header_avatar").css({ 'background-image':'none'});
            setImageOnload(a.avatarLCD, user.photo['i106x106']);
        }else{
            a.avatarLCD.css({ visibility: 'hidden'});
        }



		//profile link
		a.avatarLCD_link = $(a).find( ".timeline_a_ava_holder" );
		a.avatarLCD_link.attr('href', WHP.links.getUserProfileLink(_resp.photo.user.id));


		//photo
		a.photo = $(a).find( ".timeline_template_photo_img" );

        setImageOnload(a.photo, _resp.photo['i400x400'], $(a).find( ".timeline_template_photobody" ));

		//image link
		a.photo_link = $(a).find( ".timeline_a_image_holder" );
		a.photo_link.attr('href', WHP.links.getPhotoLink(_resp.photo.id));

		//controls
		a.likesAction = bind(this.likeAct, a);
		a.setViewLikes = bind(this.setViewLikes, a);


		a.likesControl = a.find(".timeline_likes_ico_0");
		a.likesControl.click(function(e) { a.likesAction(1); return cancelEvent(e); });

		a.setViewLikes();

		//comments count
		a.commentsControl = a.find(".timeline_comments_ico");
		a.commentsControl.find(".timeline_comments_label").text(NformatMin(a.commentsCount));
		a.commentsControl.click(bind(function() {

			WHP.controller.navigateTo(WHP.links.getPhotoLink(a.photo_id, true));
			},a));


		//add links
		addIntelloLinks(a);

		return a;
	},



	setViewLikes: function()
	{
        if (WHP.auth.status)
        {
            var wL = this.wasVote;
        }else{
            var wL = 0;
        }

        this.likesControl.removeClass().addClass("timeline_likes_ico_"+wL);
		this.likesControl.find(".timeline_likes_label").text(NformatMin(this.likesCount));
	},

	likeAct: function(_vote)
	{
        if (!WHP.auth.status)
        {
            WHP.menu.showLoginMenu2();
            return false;
        }


		if (this.wasVote == 1)
			this.likesCount--;

		if (this.wasVote == _vote)
		{
			this.wasVote = 0;
		}else{
			this.wasVote = _vote;
            this.likesCount++;
		}
		this.setViewLikes();
		WHP.actions.likes.likePhoto(this.photo_id, this.wasVote, "LIKE_TIMELINE");
	},


	createLike: function(_resp)
	{
		var user = _resp.user;
		if ((this.userObject) && (!user))
			user = this.userObject;

		var a = this.templateLike.clone();
		setFCK_FF_BKy(a.find(".timeline_v_plate"), -21);

        a.eType = "like";
		a.parent = this;
		a.timeshtamp = _resp.timestamp*1000;
		a.uid = user.id;

		//set time
		a.timeShtampLCD = a.find(".timeline_timeshtamp");
		a.timeShtampLCD.text(getTimeFormatedTl(_resp.timestamp*1000));

        a.user = user;

		//title
		a.titleLCD = $(a).find( ".timeline_header_text_cont" );
		var storyName = "<a class='feed_author_name' style='font-size:16px' href='"+WHP.links.getUserProfileLink(user.id)+"' >"+user.name+"</a><br/>";
		storyName = storyName + "<span style='font-size:15px;'>liked "+_resp.photos.length;
		if (_resp.photos.length>1)
			storyName = storyName + " photos"
		else
			storyName = storyName + " photo";
		storyName = storyName + "</span>";
		a.titleLCD.html(storyName);

		//avatar image
		a.avatarLCD = $(a).find( ".timeline_header_avatar_img" );
        if (user.photo)
        {
            $(a).find( ".timeline_header_avatar").css({ 'background-image':'none'});
            setImageOnload(a.avatarLCD, user.photo['i106x106']);
        }else{
            a.avatarLCD.css({ visibility: 'hidden'});
        }


		//profile link
		a.avatarLCD_link = $(a).find( ".timeline_a_ava_holder" );
		a.avatarLCD_link.attr('href', WHP.links.getUserProfileLink(user.id));
		a.paginL = $(a).find( ".timeline_elem_pagin_l" );
		a.paginL.click(function () { a.slidePage(-1); });
		a.paginR = $(a).find( ".timeline_elem_pagin_r" );
		a.paginR.click(function () { a.slidePage(1); });
		a.pageInd = $(a).find( ".timeline_elem_pagin_ind" );

		//animation variables
		a.animationTimer = new Timer(1000/38,30);
		a.animationTimer.onTimerEvent = bind(this.animationSlide, a);

		a.p0 = 0;
		a.p1 = 0;
		a.pC = 0;

		a.labelC = 0;

		a.curPage = 0;
		a.lastPage = 0;
		a.pageN = 6;

		//canvas etc.
		a.canvas = $(a).find( ".timeline_template_like_canvas" );
		a.addLikedImage = bind(this.addLikedImage,a);
		a.checkPaginState = bind(this.checkPaginState,a);
		a.slidePage = bind(this.slidePage,a);

		a.images = [];
		a.images_count = _resp.photos.length;
		a.pages = [];


		for (var i=0; i<_resp.photos.length; i++)
		{
            _resp.photos[i].Ncur = new Number(i);
			a.addLikedImage(_resp.photos[i], i);
		}

		a.checkPaginState();
		//add links
		addIntelloLinks(a);

		return a;
	},

    getPhotoPage : function()
    {
        var _arr = [];
        for (var i=0; i<this.parent.images.length; i++)
        {
            _arr.push({ photo : this.parent.images[i].response });
        }

        log("CURN = ["+this.N+"]");
        WHP.pages.photo.imagesList.setContent(_arr, this.N);
    },

	addLikedImage: function(_resp, _N)
	{
		var a = this.parent.templateLikeSmall.clone();
		a.image = $(a).find( ".timeline_like_img" );
        //a.imageObj = _resp;
        setImageOnload(a.image,  _resp['i106x106'], a.find( ".timeline_template_like_img_cont" ));


		a.image_link = $(a).find( ".timeline_a_ava_holder" );

        a.site_url = WHP.links.getPhotoLink(_resp.id);
        a.image_link.attr('href', a.site_url);
        a.image_link.click(bind(this.parent.getPhotoPage, a));
        a.parent = this;
        a.N = _resp.Ncur;
        a.response = _resp;
        a.photo_id = _resp.id;

		var _w = 397;
		var curP = null;
		if (this.images.length % this.pageN == 0)
		{
			var newPage = $(document.createElement("div"));
			newPage.addClass("timeline_template_like_page");
			newPage.css({ width : _w+'px'});
			this.canvas.append(newPage);
			this.pages.push(newPage);
		}
		curP = this.pages[this.pages.length-1];
		//add links
		//addIntelloLinks(a);

		if (((this.images.length % this.pageN) < Math.round(this.pageN*0.5)) && (this.images_count>Math.round(this.pageN*0.5)))
		{
			a.css({ 'margin-bottom' : 15 + 'px'});
		}

		curP.append(a);
		this.images.push(a);
	},


	slidePage: function(_a)
	{
		if ((_a>0) && (this.curPage == this.lastPage))
			return false;
		if ((_a<0) && (this.curPage == 0))
			return false;

		if (Math.abs(this.pages[this.curPage+_a].position().left - this.pC)>800)
			return false;

		this.curPage = this.curPage + _a;
		this.p0 = this.pC;
		this.p1 = this.pages[this.curPage].position().left;

		if (this.pageInd.css('display') != 'block')
		{
			setAlpha(this.pageInd, 0);
			this.pageInd.css({ display : 'block' });
		}

		var s1 =  (this.curPage*this.pageN+1);
		var s2 = Math.min( (this.curPage+1)*this.pageN, this.images_count);
		var str = "";
		if (s1==s2)
		{
			str = s1;
		}else{
			str = s1+" - "+s2;
		}
		this.pageInd.find(".timeline_elem_pagin_ind_label").text(str);

		this.animationTimer.reset();
		this.animationTimer.start();
		this.checkPaginState();
	},

	animationSlide: function(e)
	{
		var A = e.currentCount/e.repeatCount;
		//var B = (Math.sin(Math.PI*(A-0.5))+1)*0.5;

		//A1 - for movement
		var dA1 = 0.3;
		var A1 = A/(1-dA1);
		if (A1>1)
			A1 = 1;

		var dA = 0.3;
		var dY = 0.06;
		if (A1<1-dA1)
		{
			var arg = A1/(1-dA1);
			var B = Math.sin(Math.PI*0.5*arg)*(1+dY);
		}else{
			//var arg = (A-1+dA)/dA;
			//var B = 1 + (Math.cos(Math.PI*arg)+1)*0.5*dY;
			var arg = (A1-1+dA)/dA1;
			var B = 1 + Math.cos(1*Math.PI*arg)*dY*(1-arg);
		}
		//var B = Math.sin(Math.PI*A*0.5);
		this.pC = (1-B)*this.p0 + B*this.p1;


		//C for label
		var dC = 0.1;
		C = this.labelC;
		if (A<dC)
		{
			C = C + 1/(e.repeatCount*dC);
		}else if (A>1-dC)
		{
			C = C - 1/(e.repeatCount*dC);
		}
		C = Math.min(C,1);
		C = Math.max(C,0);

		this.labelC = C;
		setAlpha(this.pageInd, this.labelC);
		this.canvas.css({ left : -this.pC + 'px'});

		if (e.currentCount == e.repeatCount)
		{
			this.pageInd.css({ display : 'none' });
		}
	},

	checkPaginState: function()
	{
		this.lastPage = Math.ceil(this.images.length/this.pageN);
		if (this.images.length/this.pageN-this.lastPage > 0)
			this.lastPage++;

		if (this.images.length<=this.pageN)
		{
			this.paginL.css({display : 'none'});
			this.paginR.css({display : 'none'});
		}else{
			this.paginL.css({display : 'block'});
			this.paginR.css({display : 'block'});

			//hide pagings of page
			if (this.curPage==0)
				this.paginL.css({display : 'none'});

			//get last page
			if (this.curPage == this.lastPage-1)
				this.paginR.css({display : 'none'});
		}
	},


	createFollow: function(_resp)
	{
		var user = _resp.user;
		if ((this.userObject) && (!user))
			user = this.userObject;

		var a = this.templateFollow.clone();
		setFCK_FF_BKy(a.find(".timeline_v_plate"), -21);

        a.eType = "follow";
		a.parent = this;
		a.timeshtamp = _resp.timestamp*1000;
		a.uid = user.id;

		//set time
		a.timeShtampLCD = a.find(".timeline_timeshtamp");
		a.timeShtampLCD.text(getTimeFormatedTl(_resp.timestamp*1000));

		//title
		a.titleLCD = $(a).find( ".timeline_header_text_cont" );
		var storyName = "<a class='feed_author_name' style='font-size:16px' href='"+WHP.links.getUserProfileLink(user.id)+"' >"+user.name+"</a><br/>";
		storyName = storyName + "<span style='font-size:15px;'>subscribed to</span>";
		a.titleLCD.html(storyName);

		//avatar image
		a.avatarLCD = $(a).find( ".timeline_header_avatar_img" );
        if (user.photo)
        {
            $(a).find( ".timeline_header_avatar").css({ 'background-image':'none'});
            setImageOnload(a.avatarLCD, user.photo['i106x106']);
        }else{
            a.avatarLCD.css({ visibility: 'hidden'});
        }

		//profile link
		a.avatarLCD_link = $(a).find( ".timeline_a_ava_holder" );
		a.avatarLCD_link.attr('href', WHP.links.getUserProfileLink(user.id));
		a.paginL = $(a).find( ".timeline_elem_pagin_l" );
		a.paginL.click(function () { a.slidePage(-1); });
		a.paginR = $(a).find( ".timeline_elem_pagin_r" );
		a.paginR.click(function () { a.slidePage(1); });
		a.pageInd = $(a).find( ".timeline_elem_pagin_ind" );

		//animation variables
		a.animationTimer = new Timer(1000/38,30);
		a.animationTimer.onTimerEvent = bind(this.animationSlide, a);

		a.p0 = 0;
		a.p1 = 0;
		a.pC = 0;
		a.labelC = 0;
		a.curPage = 0;
		a.lastPage = 0;
		a.pageN = 3;

		//canvas etc.
		a.canvas = $(a).find( ".timeline_template_follow_canvas" );
		a.addFollowedUser = bind(this.addFollowedUser,a);
		a.checkPaginState = bind(this.checkPaginState,a);
		a.slidePage = bind(this.slidePage,a);
		a.images = [];
		a.images_count = _resp.users.length;
		a.pages = [];

		for (var i=0; i<_resp.users.length; i++)
		{
			a.addFollowedUser(_resp.users[i]);
		}

		a.checkPaginState();
		//add links
		addIntelloLinks(a);

		return a;
	},

	addFollowedUser: function(_resp)
	{
		var a = this.parent.templateFollowSmall.clone();
		a.image = $(a).find( ".timeline_template_follow_ava" );

		if (_resp.photo)
            setImageOnload(a.image, _resp.photo['i106x106'])
        else
            setImageOnload(a.image, "./resouce/images/public/profile_no_ava72.jpg?whp16");


		a.image_link = $(a).find( ".timeline_a_ava_holder" );
		a.image_link.attr('href', WHP.links.getUserProfileLink(_resp.id));

		a.name_label = $(a).find( ".timeline_template_follow_label" );
		a.name_label.html("<a class='feed_author_name' style='font-size:16px' href='"+WHP.links.getUserProfileLink(_resp.id)+"'>"+_resp.name+"</a>");

		var _w = 397;
		var curP = null;
		if (this.images.length % 3 == 0)
		{
			var newPage = $(document.createElement("div"));
			newPage.addClass("timeline_template_follow_page");
			newPage.css({ width : _w+'px'});
			this.canvas.append(newPage);
			this.pages.push(newPage);
		}
		curP = this.pages[this.pages.length-1];

		curP.append(a);
		this.images.push(a);
	},

	createStory: function(_resp)
	{
		var user = _resp.user;
		if ((this.userObject) && (!user))
			user = this.userObject;

		var a = this.templateStory.clone();
		setFCK_FF_BKy(a.find(".timeline_v_plate"), -60);

        a.eType = "story";
		a.parent = this;
		a.timeshtamp = _resp.timestamp*1000;
		a.uid = user.id;

		//set time
		a.timeShtampLCD = a.find(".timeline_timeshtamp");
		a.timeShtampLCD.text(getTimeFormatedTl(_resp.timestamp*1000));

		//title
		a.titleLCD = $(a).find( ".timeline_header_text_cont" );
		var storyName = getTrimmedTextToSize(_resp.story.name,20,279,true);
		var storyLink = WHP.links.getScenarioLink(_resp.story.id);
		
		storyName = "<a class='tl_theme_text' style='font-size:16px;font-weight:bold;' href='"+storyLink+"'>"+storyName+"</a><br/>";
		storyName = storyName + "by <a class='feed_author_name' style='font-size:16px' href='"+WHP.links.getUserProfileLink(user.id)+"' >"+user.name+"</a>";
		a.titleLCD.html(storyName);
		
		//avatar image
		a.avatarLCD = $(a).find( ".timeline_header_avatar_img" );

		if (user.photo)
        {
            $(a).find( ".timeline_header_avatar").css({ 'background-image':'none'});
            setImageOnload(a.avatarLCD, user.photo['i106x106']);
        }else{
            a.avatarLCD.css({ visibility: 'hidden'});
        }


		//profile link
		a.avatarLCD_link = $(a).find( ".timeline_a_ava_holder" );
		a.avatarLCD_link.attr('href', WHP.links.getUserProfileLink(user.uid));
		
			
		//photo
		a.photo = $(a).find( ".timeline_template_story_img" );
        setImageOnload(a.photo, _resp.story['i480x120'], $(a).find( ".timeline_template_storybody" ));
		
		//image link
		a.photo_link = $(a).find( ".timeline_a_image_holder" );
		a.photo_link.attr('href', storyLink);
		
		//add links
		addIntelloLinks(a);
		
		return a;
	},
	
	
	
	onError: function(response)
	{
		var status = response['status'];
		log("WHP/timeline_prot : error status = ["+status+"]");
		this.loading = false;
		if (status!=0)
		{
			this.loadElements();
		}
		//WHP.controller.showErrorPage();
	},
	
	scrollEvent: function(e)
	{
		if (!this.active)
			return false;
			
		var sensitivity = 800;

        if (!this.initLoad && (this.curTotal>0))
		if ( getScrollTop() + WHP.screenH - $(document).height() > -sensitivity )
		{
			//log("end");	
			this.loadElements();
		}
	},



    rebuildTimeline : function (_removedList, _restoreParams)
    {
        var curI = 0;
        log("------------------------");
        log("START REBUILD!");
        log("REMOVE ELEMENTS!");
        this.restoreParams = _restoreParams;

        var removedElems = 0;
        var removedHBefore = 0;
        var removedH = 0;
        while (curI<this.pages[0].elements.length)
        {
            var needDel = false;
            var curElem = this.pages[0].elements[curI];
            if (curElem.eType == "like")
            {
                //check likes
                var i=0;
                var removedLikes = 0;
                while (i<curElem.images.length)
                {
                    if (_removedList.indexOf(curElem.images[i].photo_id)>-1)
                    {
                        curElem.images[i].remove();
                        curElem.images.splice(i,1);
                        removedLikes++;

                        var storyName = "<a class='feed_author_name' style='font-size:16px' href='"+WHP.links.getUserProfileLink(curElem.user.id)+"' >"+curElem.user.name+"</a><br/>";
                        storyName = storyName + "<span style='font-size:15px;'>liked "+curElem.images.length;
                        if (curElem.images.length>1)
                            storyName = storyName + " photos"
                        else
                            storyName = storyName + " photo";
                        storyName = storyName + "</span>";
                        curElem.titleLCD.html(storyName);

                    }else{
                        i++;
                    }
                }


                //remove if no images
                if (curElem.images.length == 0)
                {
                    needDel = true;
                    log("REMOVE FROM TL LIKE");
                }else if (removedLikes>0){
                    //rebuild pages
                    log("REBUILD PAGES");
                    this.rebuildLikes(curElem);
                }
            }else if (curElem.eType == "photo")
            {
                if (_removedList.indexOf(curElem.photo_id)>-1)
                     needDel = true;
            }

            if (needDel)
            {
                removedElems++;
                log("REMOVE");
                if (curElem.positionTL<_restoreParams.scrollpos)
                    removedHBefore += curElem.outerHeight();
                removedH += curElem.outerHeight();
                curElem.remove();
                this.pages[0].elements.splice(curI,1);
            }else{
                curI++;
            }
        }
        log("DELT = ["+removedHBefore+"]");

        this.restoreParams.scrollpos = Math.max(0, this.restoreParams.scrollpos - removedHBefore);

        log("TS = ["+this.pages[0].elements[0].timeshtamp+"] LAST = ["+this.lasttimeshtamp+"]");
        if (this.pages[0].elements.length>0)
        if (this.displayLastVisit)
        if (this.lastVisitSetted)
        if (this.lasttimeshtamp>this.pages[0].elements[0].timeshtamp)
        {
            //remove lastVisitlie
            log("LAST VISIT REMOVED");

            this.templateLastvisit.detach();
        }

        this.offset = Math.max(0, this.offset - removedElems);
        if (this.usePosRecalAfterRebuild)
            this.curTotal = Math.max(0, this.curTotal - removedElems);


        //set timeout
        setTimeout(bind(this.rebuild2, this), 100);
    },

    rebuild2 : function()
    {
        if (this.showEvents)
        {
            this.notifiesObject.removeClass("timeline_float_right");
            this.notifiesObject.removeClass("timeline_float_left");
            if (Math.abs(this.curTotal-this.lastTotal) % 2 == 0)
            {
                this.notifiesObject.addClass("timeline_float_right");
            }else{
                this.notifiesObject.addClass("timeline_float_left");
            }
        }

        this.pages[0].startY = 0;
        this.pages[0].lastMargin = 0;


        for (var i=0; i<this.pages[0].elements.length;i++)
        {
            this.pages[0].elements[i].css({ 'margin-top' : 0+'px', display : 'none' });
        }

        for (var i=0; i<this.pages[0].elements.length;i++)
        {
            this.reappendBlock(this.pages[0].elements[i],this.pages[0], i);
        }

        window.scrollTo(0,this.restoreParams.scrollpos);
        WHP.menu.setShadow(this.restoreParams.scrollpos);
    },



    reappendBlock: function(_b,_canvas, _n)
    {
        var prevYend = 0;
        if (_n>0)
        {
            var pos =_canvas.elements[_n-1].position();
            prevYend = pos.top;
        }



        _b.removeClass("timeline_float_left");
        _b.removeClass("timeline_float_right");

        if ( (Math.abs(this.curTotal-this.lastTotal) - _n) % 2 == 0)
        {
            _b.addClass("timeline_float_left");

            setFCK_FF_BKx(_b.find(".timeline_v_plate"), -20);
        }else{
            _b.addClass("timeline_float_right");

            setFCK_FF_BKx(_b.find(".timeline_v_plate"), 0);
        }

        _b.css({ display : '' });

        var posC = _b.position();


        if (_n == 0)
        {
            _canvas.startY = posC.top;
            var step = _canvas.actMargin;
        }else{
            var step = posC.top - prevYend - _canvas.lastMargin;
        }

        var marginH = 0;
        if (step < _canvas.actMargin)
        {
            marginH = Math.max(_canvas.actMargin - step,0);
            _b.css({ 'margin-top' : marginH+ 'px'});
        }
        _b.positionTL = posC.top + marginH;

        _canvas.lastMargin = marginH;
    },



    rebuildLikes: function(_elem)
    {
        for (var i=0; i<_elem.images.length; i++)
        {
            var curPage =  Math.floor(i/_elem.pageN);
            _elem.pages[curPage].append(_elem.images[i]);
        }

        var totalPages = _elem.pages.length;
        var maxPages = Math.ceil(_elem.images.length/_elem.pageN);
        if (totalPages>maxPages)
        {
            //remove pages
            log("remove pages >> N = ["+(totalPages-maxPages)+"]");
            while(_elem.pages.length>maxPages)
            {
                var a = _elem.pages.pop();
                a.remove();
            }
        }

        _elem.checkPaginState();
        _elem.slidePage(-_elem.curPage);
    },


	
	setNotifies: function(_offset)
	{
		
	},
	
	clearCanvas: function()
	{
		//remove pages
		while(this.pages.length>0)
		{
			var a = this.pages.pop();
			for (var i=0; i<a.elements.length; i++)
				a.elements[i].remove();
			a.remove();
		}
		//clear notif
		if (this.showEvents)
		{
			this.notifiesObject.removeClass("timeline_float_right");
			this.notifiesObject.removeClass("timeline_float_left");
			this.notifiesObject.remove();
		}
	}
}
}





whp_rolloutstory_proto = function () { return {
	//controller parametres
	inited : false,
	
	//main objects
	mainObject  : null,
	mainCont : null,
	mainCanvas : null, 
	
	//templates
	templ_HeadStory : null,
	templ_PageImage : null,
	templ_Page : null,
	templ_Line : null,
	
	onSubscribe : null,
	onDeSubscribe : null,
	//cur variables
	lines : [],
	curLine : null,
	
	emptyElement : null,

	//data loading parametres
	controlUrl : "",	
	loading : false,
	initLoad : false,
	
	scrollToParams : {
		scroll : false,
		p0 : 0,
		p1 : 0
	},


    loadingBar : null,
    emptyTemplate : null,
    showEmpty : false,

	//feed_empty_template_medium
	//init function
	init: function (_cont)
	{
		this.mainObject = id$('rolloutstory_template');
		this.mainObject = $(this.mainObject).clone();
		this.mainObject.removeAttr('id');
		this.mainObject.css({display : 'none'});
		
		//templates
        this.emptyTemplate = $("#timeline_empty_template").clone();
        this.emptyTemplate.removeAttr('id');

		this.templ_HeadStory = $('#rolloutstory_headstory').clone();
		this.templ_HeadStory.removeAttr('id');
		
		this.templ_PageImage = $('#rolloutstory_pageimage').clone();
		this.templ_PageImage.removeAttr('id');
		
		this.templ_Page = $('#rolloutstory_page').clone();
		this.templ_Page.removeAttr('id');
		
		this.templ_Line = $('#rolloutstory_line').clone();
		this.templ_Line.removeAttr('id');
		
		this.emptyElement = $('#feed_empty_template_medium');
		this.emptyElement = this.emptyElement.clone();
        this.setUpemptyElement(this.emptyTemplate);

		//main
		this.mainCont = $(_cont);
		this.mainCont.append(this.mainObject);

        this.loadingBar = $("#notifications_loading_tab");
        this.loadingBar.css({ display : 'block', margin : 'auto', width: 50+'px'});

		//canvas
		this.mainCanvas = this.mainObject.find(".rolloutstory_container");
		
		$(this.photoContainer).append(this.emptyElement);
		$(this.emptyElement).css({display : 'none' });
		
		this.inited = true;
	},

    setUpemptyElement : function(_elem)
    {
        _elem.defText = "Your e-mail address...";
        _elem.input = _elem.find(".timeline_empty_enter");
        _elem.input.val(_elem.defText);
        _elem.inputs = _elem.find(".timeline_empty_inputs");
        _elem.outputs = _elem.find(".timeline_empty_inputs");
        _elem.parent = this;


        _elem.formButton = _elem.find(".timeline_empty_notify_0");
        if (_elem.formButton.length == 0)
            _elem.formButton = _elem.find(".timeline_empty_notify_1");

        _elem.activeSend = false;

        _elem.input.focus(bind(this.onFocus, _elem));
        _elem.input.blur(bind(this.onBlur, _elem));
        _elem.input.keyup(bind(this.checkInput, _elem));

        _elem.formButton.click(bind(this.sendRequest, _elem));

        setClass(_elem.formButton, "timeline_empty_notify_0");


        _elem.downloadButtonT = _elem.find(".timeline_empty_download_iphone");

        _elem.downloadButtonT.click(function() { WHP.stats.trackDownload("DOWNLOAD_STORIES_EMPTY") });
    },

    sendRequest : function(e)
    {
        if (this.activeSend)
            return false;

        if (!validateEmail(this.input.val()))
            return false;

        //http://weheartpics.com/api/promo/?email=rtbwerbrt%40wrerver.rr


        $.ajax({
            url:WHP.netcalls.promoCall,
            data : { r : Math.random(), email :  this.input.val() },
            timeout:WHP.netTimeOut,
            success:bind(this.parent.promoOk, this),
            error:bind(this.parent.promoFail, this)
        });
    },

    promoOk : function(e)
    {
        this.inputs.css({display : 'none'});
        setClass(this.outputs, "timeline_empty_output");
        this.outputs.css({display : 'block' }).html("We will email you when<br/>it is ready. See you soon!");
        this.activeSend = false;
    },

    promoFail : function (e)
    {
        this.inputs.css({display : 'block'});
        setClass(this.outputs, "timeline_empty_output_fail");
        this.outputs.css({display : 'block' }).html("Failed! Please, try again!");
        this.activeSend = false;
    },



    checkInput : function(e)
    {
        if (validateEmail(this.input.val()))
        {
            setClass(this.formButton, "timeline_empty_notify_1");
        }else{
            setClass(this.formButton, "timeline_empty_notify_0");
        }
    },


    onFocus : function(e)
    {
        if (this.input.val() == this.defText)
            this.input.val("");
    },

    onBlur : function(e)
    {
        if (this.input.val() == "")
            this.input.val(this.defText);
    },



    restore : function()
    {
        this.active = true;

    },
	
	show: function(_offset)
	{
		this.active = true;
		this.clearCanvas();
        this.mainObject.append(this.loadingBar);
		this.loadElements();
	},
	
	hide: function()
	{
		this.active = false;
	},
	
	loadElements: function()
	{
		if (this.loading)
			return false;
			
		if (!this.initLoad)
			WHP.controller.scrollToPos(0,0);
			
		if (this.mainObject.css('display') != 'block')
			this.mainObject.css({display : 'block'});


			
		this.loading = true;
		$.ajax({
			  url: this.controlUrl,
			  data : { r : Math.random() },
			  timeout : WHP.netTimeOut,
			  success: bind(this.onData, this),
			  error: bind(this.onError, this)
		});
	},
	
	onData: function(response)
	{
		this.loading = false;

        if (!this.active)
            return false;
		
		var resp = getObjectJson(response);		
		if (resp.error)
		{
			log("WHP/timeline_prot : error while loading page data! Err =["+response+"]");
			if (!WHP.errors.hasNetError(resp))
			{
				WHP.controller.showErrorPage();
			}
			return false;
		}

        log("START = ["+resp.dailies.length+"] ["+resp.storycats.length+"]");

        if (resp.dailies.length>0)
        {
            var daily = {
                id : 'daily',
                name : 'Daily',
                stories_completed : resp.dailies.length,
                stories_count : resp.dailies.length,
                storysets : resp.dailies
            };
            resp.storycats.push(daily);
        }


		
		var curLine = null;
		for (var i=0; i<resp.storycats.length;i++)
		{
			if (i % 3 == 0)
				curLine = this.addLine();
				
			var elem = this.createHeadStory(resp.storycats[i]);
			elem.parentLine = curLine;
			curLine.addHead(elem);
		}



        log("HERE!");
        this.loadingBar.remove();
		if (resp.storycats.length == 0)
		{

            log("L = [0]");
            if (this.showEmpty)
            {
                log("SET EMPTY!!");
                WHP.stats.trackEmptyStories();
                this.mainCanvas.append(this.emptyTemplate);
            }else{
                this.mainCanvas.append(this.emptyElement);
                this.emptyElement.css({display : 'block' });
            }

		}else{
			this.emptyElement.css({display : 'none' });
            this.emptyElement.detach();
            this.emptyTemplate.detach();
		}
		
		
		//log(response);
		//WHP.resetH();
		this.initLoad = false;
	},
	
	addLine : function()
	{
		var a = this.newLine();
		this.lines.push(a);
		this.mainCanvas.append(a);
		return a;
	},
	
	createHeadStory: function(resp)
	{
		pageBorders = 28;
		pageUp = 38;
		photoH = 231;
		
		var a = this.templ_HeadStory.clone();
		a.titleLCD = a.find(".profile_stories_elem_header_tittle");
		a.descCD = a.find(".profile_stories_elem_header_desc");
		a.image = a.find(".imgcollage_template_like_212_img");
		a.image_cont = a.find(".imgcollage_template_like_212_img_cont");
		a.click(bind(this.getStoryContent,a));
		
		a.id = resp.id;
		a.pages = [];
		
		
		a.titleLCD.text(resp.name);
		
		a.parentLine = null;


		var photoN = 0;	
		var totalH = pageBorders;
		var thumbPhoto = resp.storysets[0].photos[0];		
		for (var i=0; i < resp.storysets.length; i++)
		{
			var page = this.newPage();
			page.id = resp.storysets[i].id;
			page.titleLCD.text(resp.storysets[i].name);
			photoN += resp.storysets[i].photos.length;
			if (thumbPhoto.id < resp.storysets[i].photos[0].id)
				thumbPhoto = resp.storysets[i].photos[0];
			for (var k=0; k<resp.storysets[i].photos.length; k++)
			{
				var elem = this.createPageImage(resp.storysets[i].photos[k]);
                elem.parent = page;
                elem.N = new Number(k);
				page.elements.push(elem);
				page.contentCanvas.append(elem);
			}
			
			totalH += pageUp + photoH*Math.ceil(resp.storysets[i].photos.length/4);
			a.pages.push(page);
		}
		
		a.contentH = totalH;
		var desc = photoN+" ";
		
		if (photoN>1)
			desc += "photos in "
		else
			desc += "photo in ";
			
		if (resp.storysets.length == 1)
			desc += resp.storysets.length+" category"
		else
			desc += resp.storysets.length+" categories";




        setImageOnload(a.image, thumbPhoto['i212x212'], a.image_cont);
		a.descCD.text(desc);
		
		//a.story_id =
		
		return a;
	},
	
	getStoryContent : function()
	{
		log("getStoryContent");
		log("["+this.parentLine.curElem +"] [ "+ this.positionN+"]     ["+this.parentLine.h_p1 +"] [ "+ this.parentLine.contentH+"]")
		if ((this.parentLine.curElem != this.positionN) && (this.parentLine.h_p1 == this.parentLine.contentH) && (this.parentLine.contentH!=0))
		{
			log("!!!!RESIZE");
			this.parentLine.setN(this.positionN);
			
			//fill rnd data			
			this.parentLine.clearContent();
			this.parentLine.setLineContent();
			
			//resize
			this.parentLine.resizeContent();
		}else{
			if (this.parentLine.h_p1 == 0)
			{
				log("!!!!SHOW");
				this.parentLine.setHeadNfast( this.positionN );
				this.parentLine.showContent(this.parentLine.contentH);


                if (browser.ie)
                {
                    setTimeout(bind(function() {
                        var scrollPos = this.parentLine.offset().top-90 + getScrollTop();
                        log("scrollto = ["+scrollPos+"] ["+getScrollTop()+"]");
                        WHP.smoothScrollTo(0, scrollPos, null, true);
                    }, this), 200);
                }else{
                    var scrollPos = this.parentLine.offset().top-90;
                    log("scrollto = ["+scrollPos+"]");
                    WHP.smoothScrollTo(0, scrollPos, null, true);

                }


				
			}else{
				log("!!!!HIDE");
				this.parentLine.hideContent();
			}
		}
	},

    getPhotoPage : function()
    {
        var _arr = [];
        for (var i=0; i<this.parent.elements.length; i++)
        {
            log("i = ["+i+"]");
            _arr.push({ photo : this.parent.elements[i].response });
        }

        log("CURN = ["+this.N+"]");
        WHP.pages.photo.imagesList.setContent(_arr, this.N);
        //WHP.controller.navigateTo(this.site_url);
    },
	
	createPageImage: function(resp)
	{
		var a = this.templ_PageImage.clone();
		a.image = a.find(".img_template_like_160_img");
		a.image_link = a.find(".timeline_a_ava_holder");
		a.image_cont = a.find(".img_template_like_160_img_cont");
		a.likesLCD = a.find(".feedgrid_hearts_lcd");
		a.likesLCD_cont = a.find(".feedgrid_heart_0");
        a.fader = a.find(".img_template_like_160_img_fader");
        a.fader.css({ display : 'none'});

        a.response = resp;
        a.parent = null;
		
		//var likes = Math.max(0, Math.round(Math.random()*1200-100));
		var likes = resp.like;
		a.likesLCD.text( NformatMin( likes ) );


        if (resp.wasvote==1)
        {
            setClass(a.likesLCD_cont, "feedgrid_heart_1");
        }

        setImageOnload(a.image, resp['i212x212'], a.image_cont, bind(this.faderHider, a));
        a.site_url = WHP.links.getPhotoLink(resp.id);
        a.image_link.click(bind(this.getPhotoPage, a));
		a.image_link.attr('href', a.site_url);

		//a.likesCount =
		//a.dislikesCount =
		//a.photo_id =
		return a;
	},

    faderHider : function()
    {
       this.fader.css({display : ''});
    },
	
	newPage: function()
	{
		var a = this.templ_Page.clone();
		a.titleLCD = a.find(".page_template_header");
		a.contentCanvas = a.find(".page_template_container");
		a.elements = [];
		
		return a;
	},
	
	newLine: function()
	{
		var a = this.templ_Line.clone();
		a.parent = this;
		a.headCanvas = a.find(".stories_line_cont");
		a.contentCanvas = a.find(".story_line_rollover_place_cont");
		a.contentCont = a.find(".story_line_rollover_place");
		a.elementsV = a.find(".story_line_top_v");
		

		//H rollover
		a.contentCont.css({ height : 0 });
		a.elementsV.css({visibility : 'hidden'});
		
		a.moveHTimer = new Timer(1000/30, 10);
		a.moveHTimer.onTimerEvent = bind( this.moveHevent, a);
		a.h_cur = 0;
		a.h_p0 = 0;
		a.h_p1 = 0;
		a.contentH = 0;
		
		a.showContent = bind(this.showContent, a);
		a.hideContent = bind(this.hideContent, a);
		a.resizeContent = bind(this.resizeContent, a);
		//arrays
		a.headElements = [];
		a.contentElements = [];
		
		//clear containers
		a.clearHead = bind(this.clearHead_line, a);
		a.clearContent = bind(this.clearContent_line, a);
		a.clearAll = bind(this.clearLineContent, a);
		
		//add to containers
		a.addHead = bind(this.addHead_line, a);
		a.addContent = bind(this.addContent_line, a);
		a.setLineContent = bind(this.setLineContent, a);
		
		//V move
		a.curElem = -1;
		a.setN = bind(this.setHeadN, a);
		a.setHeadNfast = bind(this.setHeadNfast, a);
		a.moveVTimer = new Timer(1000/30, 10);
		a.moveVTimer.onTimerEvent = bind( this.moveVevent, a);
		a.v_cur = 0;
		a.v_p0 = 0;
		a.v_p1 = 0;
		
		return a;
	},
	
	clearLineContent : function()
	{
		this.clearHead();
		this.clearContent();
	},
	
	setLineContent : function(_N)
	{
		log("Cur elem = ["+this.headElements[this.curElem].pages.length+"]");
		for (var i=0; i< this.headElements[this.curElem].pages.length; i++)
		{
			this.addContent(this.headElements[this.curElem].pages[i]);
		}
		addIntelloLinks(this.contentCanvas);	
		this.contentH = this.headElements[this.curElem].contentH;
	},
	
	
	resizeContent : function()
	{
		log("resizeContent");
		//timers
		this.parent.scrollToParams.scroll = false;
		this.h_p0 = this.h_cur;
		this.h_p1 = this.contentH;
		this.moveHTimer.reset();
		this.moveHTimer.repeatCount = Math.round(Math.abs(this.h_p0-this.h_p1)/100) + 10;
		this.moveHTimer.start();
	},
	
	showContent : function()
	{
		log("ShowContent");		
		//if (this.parent.curLine != null)
		//	this.parent.curLine.hideContent();
		this.parent.curLine = this;
		this.parent.scrollToParams.scroll = true;
		
		this.parent.scrollToParams.p0 = $(document).scrollTop();
		this.parent.scrollToParams.p1 = this.parent.curLine.offset().top;
		
		this.clearContent();
		this.setLineContent();
		
		//timers
		this.h_p0 = this.h_cur;
		this.h_p1 = this.contentH;
		this.moveHTimer.reset();
		this.moveHTimer.repeatCount = Math.round(Math.abs(this.h_p0-this.h_p1)/100) + 10;
		this.moveHTimer.start();
		
		this.moveVTimer.stop();
	},
	
	hideContent : function()
	{
		log("HideContent");
		this.curElem = -1;
		this.parent.scrollToParams.scroll = false;
		
		this.h_p0 = this.h_cur;
		this.h_p1 = 0;
		this.moveHTimer.reset();
		this.moveHTimer.start();
		
		this.moveVTimer.stop();
	},
	
	moveHevent : function(e)
	{
		var A = e.currentCount/e.repeatCount;
		//var B = Math.sin(Math.PI*0.5*A);
		var B = (Math.sin(Math.PI*(A-0.5))+1)*0.5;
		this.h_cur = (1-B)*this.h_p0  + B*this.h_p1;
		
		this.contentCont.css({ height : this.h_cur });
		
		if (this.parent.scrollToParams.scroll)
		{
			this.parent.scrollToParams.p1 = this.parent.curLine.offset().top-80;
			var newPos = (1-B)*this.parent.scrollToParams.p0 + B*this.parent.scrollToParams.p1;
			//window.scrollTo(0, newPos);
		}
		
		
		
		
		//V display 
		if ( this.h_cur>30 )
		{
			if (this.elementsV.css('visibility') != 'visible')
				this.elementsV.css({visibility : 'visible'});
		}else{
			if (this.elementsV.css('visibility') != 'hidden')
				this.elementsV.css({visibility : 'hidden'});
		}

        if (A==1)
        {
            //WHP.resetH();
        }
	},
	
	
	
	moveVevent : function(e)
	{
		var A = e.currentCount/e.repeatCount;
		var B = Math.sin(Math.PI*0.5*A);
		this.v_cur = (1-B)*this.v_p0  + B*this.v_p1;
		
		this.elementsV.css({ left : this.v_cur + 'px' });
	},
	
	setHeadN : function(_N)
	{
		log("SetHeadN");
		this.curElem = _N;
		var b = 140;
		var a = 263+51;
		
	
		this.v_p0 = this.v_cur;
		this.v_p1 = (a*this.curElem+b);
		
		this.moveVTimer.reset();
		this.moveVTimer.start();
	},
	
	setHeadNfast : function(_K)
	{
		this.curElem = _K;
		var b = 140;
		var a = 263+51;
		
		this.v_cur = (a*this.curElem+b);
		this.elementsV.css({ left : this.v_cur + 'px' });
	},
	
	
	addHead_line: function(_elem)
	{
		_elem.positionN = parseInt(new Number(this.headElements.length));
		this.headElements.push(_elem);
		this.headCanvas.append(_elem);
	},
	
	addContent_line: function(_elem)
	{
		_elem.positionN = parseInt(new Number(this.contentElements.length));
		this.contentElements.push(_elem);
		this.contentCanvas.append(_elem);
	},
	
	clearHead_line: function()
	{
		while( this.headElements.length > 0 )
		{
			var a = this.headElements.pop();
			a.remove();
		}
	},
	
	clearContent_line: function()
	{
		while( this.contentElements.length > 0 )
		{
			var a = this.contentElements.pop();
			a.remove();
		}
	},
	
	onError: function(response)
	{
		var status = response['status'];
		log("WHP/timeline_prot : error status = ["+status+"]");
		this.loading = false;
		if (status!=0)
		{
			log("Reload data");
			this.loadElements();
		}
		//WHP.controller.showErrorPage();
	},
	
	clearCanvas: function()
	{
		//remove pages
		while(this.lines.length>0)
		{
			var a = this.lines.pop();
			a.remove();
		}
		$(this.emptyElement).css({display : 'none'});
	}
}
}



whp_subscribers_proto = function () { return {
	//controller parametres
	inited : false,
	
	//main objects
	mainObject  : null,
	mainCont : null,
	mainCanvas : null, 
	nameLabel : null,
	loadingBar : null,
	
	
	//templates
	templElement : null,
	curOffset : 0,
	curTotal : 0,
	elementsLimit : 200,
	
	//cur variables
	elements : [],
	onSubscribe : null,
	onDeSubscribe : null,
		
	
	//data loading parametres
	controlUrl : "",	
	loading : false,
	initLoad : false,
	
	controlCanvas : true,
	changeUrl : true,

    emptyElement : null,
    clearOnLoad : false,

    onDataLoaded : null,
	

	//init function
	init: function (_cont)
	{
		this.mainObject = $('#subscribers_template');
		this.mainObject = $(this.mainObject).clone();
		this.mainObject.removeAttr('id');
		this.mainObject.css({display : 'none'});



		
		//templates
		this.templElement = $('#user_follower_template').clone();
		this.templElement.removeAttr('id');
		
		this.loadingBar = id$("notifications_loading_tab" );
		this.loadingBar = $(this.loadingBar).clone();
		this.loadingBar.css({ display : 'none', width : 100+"%"});


        this.emptyElement = $('#feed_empty_template_medium').clone();
        this.emptyElement.removeAttr("id");
	
		//main
		this.mainCont = $(_cont);
		this.mainCont.append(this.mainObject);
		
		//canvas
		this.nameLabel = this.mainObject.find(".feed_name");
		this.mainCanvas = this.mainObject.find(".subscribers_content_box");

		
		//add scroll event for end check
		var mousewheelevt = (/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel";	
		AddHandler(document, mousewheelevt, bind(this.scrollEvent,this));
		
		
		this.inited = true;
	},

    restore : function()
    {
        this.active = false;

    },

    refresh : function()
    {
        this.clearOnLoad = true;
        this.curOffset = 0;
        this.curTotal = 0;
        this.initLoad = true;
        this.loadElements();
    },
	
	show: function()
	{
		this.active = true;
		this.curOffset = 0;
		this.curTotal = 0;
		
		this.clearCanvas();
		this.initLoad = true;
		
		this.mainCanvas.append( this.loadingBar );
		this.loadElements();
	},
	
	hide: function()
	{
		this.active = false;
	},

    hasElement : function(_id)
    {
        var has1 = false;

        for (var i=0; i< this.elements.length;i++)
        {
            if (this.elements[i].id == _id)
            {
                has1 = true;
                break;
            }
        }

        return has1;
    },

	setName: function(str)
	{
		this.nameLabel.text(str);
	},
	
	loadElements: function()
	{
		if (this.loading)
			return false;
			
		if ((this.curOffset >= this.curTotal) && (this.curOffset!=0))
			return false;
			
		if (!this.initLoad && (this.curTotal==0))
			return false;
		
		if ((!this.initLoad) && (this.controlCanvas) && (this.curOffset==0))
			WHP.controller.scrollToPos(0,0);
			
		if (this.mainObject.css('display') != 'block')
			this.mainObject.css({display : 'block'});
			
		//log("Load = ["+this.curOffset+"] ["+this.elementsLimit+"]");
			
		this.loading = true;
		this.jqxhr = $.ajax({
			  url: this.controlUrl,
			  timeout : WHP.netTimeOut,
			  data : { offset : this.curOffset, limit : this.elementsLimit, r : Math.random() },
			  success: bind(this.onData, this),
			  error: bind(this.onError, this)
		});
		this.loadingBar.css({ display : 'block'});
        this.emptyElement.remove();
	},
	
	onData: function(response)
	{
		this.loading = false;

        if (!this.active)
            return false;

		var resp = getObjectJson(response);	
		if (resp.error)
		{
			log("WHP/timeline_prot : error while loading page data! Err =["+response+"]");
			if (!WHP.errors.hasNetError(resp))
			{
				WHP.controller.showErrorPage();
			}
			return false;
		}

		//log("DATA");
        if (this.clearOnLoad)
        {
            this.clearOnLoad = false;
            this.clearCanvas();
        }
		
		var respC = resp.followers;
		if (!respC)
			respC = resp.followings;
		
		this.curTotal = respC.total;

        if (this.onDataLoaded)
            this.onDataLoaded(resp);

		this.curOffset = this.curOffset + respC.list.length;
		
		
			
		
		
		this.addContent(resp);

        if (this.curTotal == 0)
            this.mainCanvas.append(this.emptyElement);

		this.loadingBar.insertAfter(this.elements[this.elements.length-1]);
		if (this.curOffset >= this.curTotal)
			this.loadingBar.css({ display : 'none'});
			
		//WHP.resetH();
		this.initLoad = false;
	},
	
	onError : function(response)
	{
		var status = response['status'];
		//log("error loading");
		this.loadingBar.css({ display : 'none'});
		this.loading = false;
	},
	
	addContent : function(resp)
	{
		var arr = resp.followings;
		if (!arr)
			arr = resp.followers;	
			
		for (var i=0; i< arr.list.length;i++)
		{
            if (!this.hasElement(arr.list[i].id))
            {
                var a = this.newUser(arr.list[i]);
                this.mainCanvas.append(a);
                this.elements.push (a);
            }
		}
		addIntelloLinks(this.mainCanvas);
	},
	
	newUser: function(resp)
	{
		var element_div = this.templElement.clone();
		element_div.name = element_div.find(".followers_name");
		element_div.followButton = element_div.find(".unfollow_button");
		element_div.buttonLabl = element_div.find(".unfollow_button_label");
		
		//log("user = ["+resp.id+"] follow = ["+resp.follow+"]");
		element_div.uid = resp.id;
		element_div.follow = resp.follow;		
		element_div.parent = this;
        element_div.activeNet = false;
		element_div.followButton.click(bind(this.followClick,element_div));
		
		element_div.name.attr('href', WHP.links.getUserProfileLink( element_div.uid ));
		
		element_div.setButtonLabel = bind(this.setButtonLabel,element_div);
		element_div.followResponse = bind(this.followResponse,element_div);
		element_div.followError = bind(this.followError,element_div);
		element_div.setFollowersLabels = bind(this.setFollowersLabels,this);
		
		element_div.setButtonLabel();
		element_div.name.text(resp.name);
		
		return element_div;
	},
	
	setButtonLabel: function (_q)
	{
		var labl = this.buttonLabl;
		
		if (WHP.auth.status)
		{
			//log(" ids = ["+this.uid+"] ["+WHP.auth.status.id+"]");
			if (this.uid == WHP.auth.status.id)
			{
				this.followButton.css({ visibility : 'hidden' });
			}else{
				this.followButton.css({ visibility : 'visible' });
				if (this.follow)
				{
					labl.html("Remove")
					setClass(this.followButton, "unfollow_button");
				}else{
					labl.html("Subscribe");
					setClass(this.followButton, "unfollowb_button");
				}
			}
			//this.followButton.css({ visibility : 'visible' });
		}else{
			this.followButton.css({ visibility : 'visible' });
			labl.html("Subscribe");
			setClass(this.followButton, "unfollowb_button");
			//this.followButton.css({ visibility : 'hidden' });
		}		
	},
	
	setFollowersLabels: function(_a)
	{
		if (this.onSubscribe)
			this.onSubscribe(_a);
	},
	
	followClick: function()
	{
        if (this.activeNet)
            return false;

		if (!WHP.auth.status)
		{
			WHP.menu.showLoginMenu2();
			return false;	
		}
		
		var call = WHP.netcalls.followCall;
		
		if (this.follow)
        {
			call = WHP.netcalls.unfollowCall;
        }else{
            WHP.opengraph.makeFolowAction(this.uid);
        }

        this.activeNet = true;
		this.buttonLabl.html("<div class='button_loading'></div>");		
		$.ajax({
			  url: call ,
              data : { user : this.uid, r : Math.random() },
			  timeout : WHP.netTimeOut,
			  success: bind(this.followResponse, this),
			  error: bind(this.followError, this)
		});
	},
	
	followResponse: function(response)
	{
        this.activeNet = false;
		var resp = getObjectJson(response);			
		if (resp.error)
		{
			WHP.errors.hasNetError(resp);
			return false;
		}	
		if (resp.status == "OK")
		{
			this.follow = !this.follow;
			if (this.follow)
				this.setFollowersLabels( 1)
			else
				this.setFollowersLabels(-1);
			this.setButtonLabel();
		}
	},
	
	followError: function(e)
	{
        this.activeNet = false;
		log("Follow error");
	},
	
	clearCanvas: function()
	{
		//remove pages
		while(this.elements.length>0)
		{
			var a = this.elements.pop();
			a.remove();
		}
	},
	
	scrollEvent: function(e)
	{
		if (!this.active)
			return false;
			
		var sensitivity = 50;
		if ($(document).scrollTop()+WHP.screenH-$(document).height()>-sensitivity)
		{
			//log("end");	
			this.loadElements();
		}
	},

    removeElement : function(_id)
    {
        var elem = null;
        log("start detection");
        for (var i = 0; i< this.elements.length; i++)
        {
           log("e.id = ["+this.elements[i].uid+"] ["+_id+"]");
           if (this.elements[i].uid == _id)
           {
                //remove
               var a = this.elements[i];
               a.remove();
               this.elements.splice(i,1);
               break;
           }
        }

        //WHP.resetH();

        return true;
    },

    addElement : function(_elem)
    {
        log("Add elem");
        var element_div = this.templElement.clone();
        element_div.name = element_div.find(".followers_name");
        element_div.followButton = element_div.find(".unfollow_button");
        element_div.buttonLabl = element_div.find(".unfollow_button_label");

        //log("user = ["+resp.id+"] follow = ["+resp.follow+"]");
        element_div.uid = _elem.uid;
        element_div.follow = true;
        element_div.parent = this;
        element_div.followButton.click(bind(this.followClick,element_div));

        element_div.name.attr('href', WHP.links.getUserProfileLink( element_div.uid ));

        element_div.setButtonLabel = bind(this.setButtonLabel,element_div);
        element_div.followResponse = bind(this.followResponse,element_div);
        element_div.followError = bind(this.followError,element_div);
        element_div.setFollowersLabels = bind(this.setFollowersLabels,this);

        element_div.setButtonLabel();
        element_div.name.text(_elem.username);
        addIntelloLinks(element_div);

        this.emptyElement.remove();


        this.curTotal++;
        this.mainCanvas.prepend( element_div );
        this.elements.push ( element_div );
    }
}
}



whp_newfaces_proto = function () { return {
	//controller parametres
	inited : false,
	
	//main objects
	mainObject  : null,
	mainCont : null,
	mainCanvas : null, 
	nameLabel : null,
	loadingBar : null,
	
	
	//templates
	templElement : null,
	curOffset : 0,
	curTotal : 0,
	elementsLimit : 666,
	
	//cur variables
	elements : [],
    sizeE : 0,
	onSubscribe : null,
	onDeSubscribe : null,
    onDataLoad : null,
		
	
	//data loading parametres
	controlUrl : "",	
	loading : false,
	initLoad : false,
	
	controlCanvas : true,
	changeUrl : true,
	

	//init function
	init: function (_cont)
	{
		this.mainObject = $('#subscribers_template');
		this.mainObject = $(this.mainObject).clone();
		this.mainObject.removeAttr('id');
		this.mainObject.css({display : 'none'});
		
		//templates
		this.templElement = $('#user_followers_template').clone();
		this.templElement.removeAttr('id');
		
		this.loadingBar = id$("notifications_loading_tab" );
		this.loadingBar = $(this.loadingBar).clone();
		this.loadingBar.css({ display : 'none', width : 100+"%"});
	
		//main
		this.mainCont = $(_cont);
		this.mainCont.append(this.mainObject);
		
		//canvas
		this.nameLabel = this.mainObject.find(".feed_name");
		this.mainCanvas = this.mainObject.find(".subscribers_content_box");
		
		//add scroll event for end check
		var mousewheelevt = (/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel";	
		AddHandler(document, mousewheelevt, bind(this.scrollEvent,this));
		
		
		this.inited = true;
	},
	
	show: function()
	{
		this.active = true;
		this.curOffset = 0;
		this.curTotal = 0;
		
		this.clearCanvas();
		this.initLoad = true;

        this.mainObject.css({display : 'none'});
		this.mainCanvas.append( this.loadingBar );
		this.loadElements();
	},

    restore : function()
    {
        this.active = true;
    },
	
	hide: function()
	{
		this.active = false;
	},
	
	setName: function(str)
	{
		this.nameLabel.text(str);
	},
	
	loadElements: function()
	{
		if (this.loading)
			return false;
			
		if ((this.curOffset >= this.curTotal) && (this.curOffset!=0))
			return false;
			
		if (!this.initLoad && (this.curTotal==0))
			return false;
		
		if ((!this.initLoad) && (this.controlCanvas) && (this.curOffset==0))
			WHP.controller.scrollToPos(0,0);

			
		log("Load = ["+this.curOffset+"] ["+this.elementsLimit+"]");
			
		this.loading = true;
		this.jqxhr = $.ajax({
			  url: this.controlUrl,
			  timeout : WHP.netTimeOut,
			  data : { offset : this.curOffset, limit : this.elementsLimit, r : Math.random() },
			  success: bind(this.onData, this),
			  error: bind(this.onError, this)
		});
		this.loadingBar.css({ display : 'block'});
	},
	
	onData: function(response)
	{
		this.loading = false;

        if (!this.active)
            return false;


		var resp = getObjectJson(response);	
		if (resp.error)
		{
			log("WHP/timeline_prot : error while loading page data! Err =["+response+"]");
			if (!WHP.errors.hasNetError(resp))
			{
				WHP.controller.showErrorPage();
			}
			return false;
		}
		//log("DATA");
		
		var respC = resp.newfaces;
		
		this.curTotal = respC.total;

        if (this.curTotal>0)
            this.mainObject.css({display : 'block'})
        else
            this.mainObject.css({display : 'none'});

		this.curOffset = this.curOffset + respC.list.length;
		
			
		//dataload
		if (this.onDataLoad)
            this.onDataLoad(resp);

		this.addContent(resp);
		
		this.loadingBar.insertAfter(this.elements[this.elements.length-1]);
		if (this.curOffset >= this.curTotal)
			this.loadingBar.css({ display : 'none'});
			
		//WHP.resetH();
		this.initLoad = false;
	},
	
	onError : function(response)
	{
		var status = response['status'];
		//log("error loading");
		this.loadingBar.css({ display : 'none'});
		this.loading = false;
	},
	
	addContent : function(resp)
	{
		var arr = resp.newfaces;

        for (var i=0; i< arr.list.length;i++)
		{
			var a = this.newUser(arr.list[i]);
			this.mainCanvas.append(a);
			this.elements.push (a);
		}
		addIntelloLinks(this.mainCanvas);
	},
	
	newUser: function(resp)
	{
		var element_div = this.templElement.clone();
		element_div.name = element_div.find(".followers_name");
        element_div.resp = resp;

		element_div.followButton = element_div.find(".unfollow_button");
		element_div.buttonLabl = element_div.followButton.find(".unfollow_button_label");

        element_div.okButton = element_div.find(".unfollowb_button");
        element_div.okbuttonLabl = element_div.okButton.find(".unfollow_button_label");
		
		//log("user = ["+resp.id+"] follow = ["+resp.follow+"]");
		element_div.uid = resp.id;
		element_div.follow = null;
		element_div.parent = this;
        element_div.username = resp.name;
        element_div.activeNet = false;

		element_div.followButton.click(bind(this.unfollowClick,element_div));
        element_div.okButton.click(bind(this.followClick,element_div));
		
		element_div.name.attr('href', WHP.links.getUserProfileLink( element_div.uid ));
		
		element_div.setButtonLabel = bind(this.setButtonLabel,element_div);
		element_div.followResponse = bind(this.followResponse,element_div);
		element_div.followError = bind(this.followError,element_div);
		
		element_div.setButtonLabel();
		element_div.name.text(resp.name);
		
		return element_div;
	},

	
	setButtonLabel: function (_q)
	{
        this.buttonLabl.html("Remove")
        setClass(this.followButton, "unfollow_button");

        this.okbuttonLabl.html("Ok")
        setClass(this.okButton, "unfollowb_button");
    },

    unfollowClick: function()
    {
        call = WHP.netcalls.unfollowCall;
        this.follow = false;

        this.buttonLabl.html("<div class='button_loading'></div>");
        $.ajax({
            url: call,
            data : { r :Math.random(), user : this.uid },
            timeout : WHP.netTimeOut,
            success: bind(this.followResponse, this),
            error: bind(this.followError, this)
        });
    },


	followClick: function()
	{
        if (this.activeNet)
            return false;

		var call = WHP.netcalls.followCall;
        this.follow = true;
        this.activeNet = true;
		this.okbuttonLabl.html("<div class='button_loading'></div>");
        WHP.opengraph.makeFolowAction(this.uid);
		$.ajax({
			  url: call,
              data : { r :Math.random(), user : this.uid },
			  timeout : WHP.netTimeOut,
			  success: bind(this.followResponse, this),
			  error: bind(this.followError, this)
		});
	},
	
	followResponse: function(response)
	{
        this.activeNet = false;
        var e = { target : this, follow : this.follow };
        if (this.follow)
        {
            if (this.parent.onSubscribe)
                this.parent.onSubscribe(e,this);
        }else{
            if (this.parent.onDeSubscribe)
                this.parent.onDeSubscribe(e,this);
        }


        this.parent.curTotal--;
        if (this.parent.curTotal==0)
        {
            this.parent.mainObject.css({display : 'none'});
        }
		this.remove();
	},
	
	followError: function(e)
	{
        this.activeNet = false;
		log("Follow error");
	},
	
	clearCanvas: function()
	{
		//remove pages
		while(this.elements.length>0)
		{
			var a = this.elements.pop();
			a.remove();
		}
	},
	
	scrollEvent: function(e)
	{
		if (!this.active)
			return false;
			
		var sensitivity = 50;
		if ($(document).scrollTop()+WHP.screenH-$(document).height()>-sensitivity)
		{
			//log("end");	
			this.loadElements();
		}
	}
}
}





WHP.links = {
	
	getUserProfileLink : function(_id)
	{
        return "//"+WHP.domain+"/user/"+_id+"/";
	},
	getPhotoLink : function(_id, _comments)
	{
		var preLink = "";
		if (_comments)
			preLink = "comments/"
		return "//"+WHP.domain+"/photo/"+_id+"/"+preLink;
	},
	getScenarioLink : function(_id)
	{
		return "//"+WHP.domain+"/story/"+_id+"/";
	},
    getStoriesLinkDaily : function()
    {
        return "//"+WHP.domain+"/stories/daily/";
    },
    getStoriesLink : function(_catId, _subcatId)
    {
        if (!_catId)
        {
            return "//"+WHP.domain+"/stories/";
        }else{
            if (!_subcatId)
            {
                return "//"+WHP.domain+"/stories/"+_catId+"/";
            }else{
                return "//"+WHP.domain+"/stories/"+_catId+"/"+_subcatId+"/";
            }
        }
    }
}






WHP.randomPage = {
    randomPicsIds : [],
    randomCount : 0,
    active : false,
	
	clickButton: function (e)
	{
        WHP.stats.trackShuffle();
		this.getRnd();
	},
	
	getRnd: function (_param)
	{
        if (this.active)
            return false;
		WHP.controller.hideCanvas();

        this.active = true;
        $.ajax({
            url: WHP.netcalls.randomImageCall,
            data : { r : Math.random() },
            timeout : WHP.netTimeOut,
            success: bind(this.rndImageCallback, this),
            error: bind(this.onError, this)
        });
    },


    checkRnd : function(_id)
    {
        var ret = false;
        for (var i=0; i<this.randomPicsIds.length;i++)
        {
           // log("rnd check = ["+this.randomPicsIds[i] +"] = ["+ _id+"]");
            if (this.randomPicsIds[i] == _id)
            {
                ret = true;
                break;
            }
        }

        return ret;
    },

    clearCHrnd : function()
    {
        if (this.randomPicsIds.length == 0)
            return false;

        this.randomPicsIds = [];
    },
	
	rndImageCallback : function (response, status)
	{
        this.active = false;
		var resp = getObjectJson(response);	
		if (resp.error)
		{
			log("WHP/random : get picture error = ["+resp.error.code+"]");
			if (!WHP.errors.hasNetError(resp))
			{
				WHP.controller.showErrorPage();
			}
			return false;
		}


        var maxRndC = 30;
        if (this.checkRnd(resp.photo.id))
        {
            this.randomCount++;
            if (this.randomCount < maxRndC)
            {
                log("["+this.randomCount+"] RND FAIL!  totalL = ["+this.randomPicsIds.length+"] picID = ["+resp.photo.id+"]");
                this.getRnd();
                return false;
            }else{
                log("RND TOTAL FAILED!!! COUNT = ["+this.randomCount+"]");
            }
        }
        this.randomCount = 0;
        if (this.randomCount < maxRndC)
            this.randomPicsIds.push(resp.photo.id);


		//set photo page
		var page = WHP.pages.photo;
		WHP.controller.clearCurPage();
		WHP.controller.setPage(page);

		//set main variables



        page.curPageId = resp.photo.id;
        page.curPageObject = resp;
        page.mainImage.likeShadow.css({ visibility : 'hidden'});

        page.setSizes();
        page.setImage(resp);


		page.comments.clearComments();
		page.comments.getComments();
		page.likeLists.getLikesLists();
		page.share.resetShare();
        page.removePhoto.checkButtonVisibility();

		var str = WHP.links.getPhotoLink(resp.photo.id);
		setLink(str);
        WHP.menu.currentMenuPos();
		page.setTitle(resp);

		WHP.controller.showCanvas();
		WHP.menu.currentMenuPos();

        WHP.controller.scrollToPos(0,0);
	},


	onError : function (e)
	{
        this.active = false;
		log("WHP/random : Error while loading actual data! : ["+e+"]");
		WHP.controller.showErrorPage();
	}
}



WHP.notifications = {
	
	
	inited : false,
	
	wind : null, 
	windCont : null,
	itemsCanvas : null,
	
	templateLike : null,
	templateComment : null,
    templateReply : null,
	templateFollow : null,
	
	loadingBar : null,
	nonotifBar : null,
	
	
	lastId : null,
	items : [],
	loading : false,
	curOffset : 0,
	maxCount : 30,
	
	totalN : 0,
	newN : 0,
	
	LPtimer : -1,
	LPtimerDelay : 1000,
	LPtimerAdapt : 1,
	LPtimerTimeout : 40000,
	
	visible : false,

    templateEmpty : null,

    pagesN : 0,
	//init function
	init: function ()
	{		
		this.wind = new whp_window_proto();
		this.windCont = id$('notifications_window');
		this.wind.init(this.windCont);
		this.wind.clearOnShow = true;
		this.wind.onEndFunc = bind(this.loadNotifications, this);
		
		this.itemsCanvas = this.wind.itemsCanvas;
		
		this.templateLike = $('#notifications_element_like');
		this.templateLike.removeAttr('id');
		this.templateComment = $('#notifications_element_comment');
		this.templateComment.removeAttr('id');
        this.templateReply = $('#notifications_element_reply');
        this.templateReply.removeAttr('id');
		this.templateFollow = $('#notifications_element_follow');
		this.templateFollow.removeAttr('id');
		
		this.loadingBar = $("#notifications_loading_tab" );
		this.loadingBar = $(this.loadingBar).clone();
		this.loadingBar.css({ display : 'none'});
		
		this.notifyBar = id$("window_prot_nonotif" );
		this.notifyBar = $(this.notifyBar).clone();
		this.notifyBar.css({ display : 'none'});

        this.templateEmpty = $("#feed_empty_template_small");
				
		this.inited = true;
	},
	
	show: function ()
	{
		this.setNotifyPos();		
		this.loading = false;
		this.curOffset = 0;
		this.totalN = 0;
        this.pagesN = 0;
		this.wind.show();	
		$(this.itemsCanvas).append( this.loadingBar );
		this.loadNotifications();

        //clear canvas
        while (this.items.length>0)
        {
            this.items.pop().remove();
        }
		
		//clearEvents if new>0

		
		//WHP.resetH();
	},
	
	setNotifyPos: function ()
	{
		var a = document.getElementById("controls_notify_middle");
		this.wind.setPos(-a.offsetWidth*0.5-12, 4);
	},
	
	clickButton: function (e)
	{
        if (WHP.download.wind.visible)
            WHP.download.hide();

		if (!this.wind.visible)
			this.show()
		else
			this.hide();
		return cancelEvent(e);
	},
	hide: function ()
	{
        if (this.wind.visible)
        {
            WHP.stats.trackNotifications(this.pagesN);
        }
		this.wind.hide();
	},
	
	
	clearEvents : function (e)
	{
		if (this.items.length>0)
		{

			$.ajax({
				  url: WHP.netcalls.clearCall+"?r="+Math.random(),
				  data : { last_event_id : this.items[0].image_id },
				  timeout : WHP.netTimeOut,
				  success: bind(this.onClearEvents, this),
				  error: bind(this.onError, this)
				});
		}
	},
	onClearEvents : function (response, status, xhr)
	{
		var resp = getObjectJson(response);	
		if (resp.error)
		{
			log("WHP/notifications : error while loading page data!");
			WHP.errors.hasNetError(resp);
			return false;
		}
		this.newN = 0;
		WHP.controller.setTitle();
		this.setNumber(this.newN);
	},
	loadNotifications: function (_a)
	{
		if (_a)
		{
			$.ajax({
					  url: WHP.netcalls.eventsCountCall,
                      data : { r : Math.random() },
					  timeout : WHP.netTimeOut,
					  success: bind(this.onDataStartNotify, this),
					  error: bind(this.onError, this)
					});
		}else{
			if ((this.curOffset < this.totalN) || (this.curOffset == 0))
			if (!this.loading)
			{
				//limit = [30,30+deltN]
				var deltN = 8;
				var count = getILimit(this.curOffset, this.totalN, deltN, this.maxCount);

                this.pagesN++;
				$.ajax({
					  url: WHP.netcalls.eventsCall+"?r="+Math.random(),
					  data : { offset : this.curOffset, limit : count },
					  timeout : WHP.netTimeOut,
					  success: bind(this.onData, this),
					  error: bind(this.onError, this)
					});
				this.loadingBar.css({ display : 'block'});
				this.loading = true;
			}
		}
	},	
	onDataStartNotify : function (response, status, xhr)
	{
		var resp = getObjectJson(response);	
		if (resp.error)
		{
			log("WHP/notifications : error while loading page data!");
			WHP.errors.hasNetError(resp);
			return false;
		}
		this.totalN = resp.events.total;
		this.newN = resp.events.new_count;
		WHP.controller.setTitle();
		this.setNumber(this.newN);

		this.startLPTimer();
	},
	onData : function (response, status, xhr)
	{
		this.loading = false;
		var resp = getObjectJson(response);	
		if (resp.error)
		{
			log("WHP/notifications : error while loading page data!");
			WHP.errors.hasNetError(resp);
			return false;
		}
		var wind_H = 0;
		
		if (this.items.length>0)
		{
			elem = this.items[this.items.length-1];
			elem.wrapper.style.display = "block";
		}
			
		for (var i=0; i<resp.events.list.length; i++)
		{
			var elem = this.getEventElem(resp.events.list[i]);
			if (i == resp.events.list.length-1)
			{
				elem.wrapper.style.display = "none";
			}else if ((resp.events.list[i]['new']) && (!resp.events.list[i+1]['new'])){
				elem.wrapper.style.top = 0+'px';
			}


			
			this.itemsCanvas.appendChild(elem.get()[0]);
			
			
			if ((i<5) && (this.curOffset == 0))
			{
				wind_H = wind_H + elem[0].offsetHeight;
			}
			
			this.items.push(elem);
		}
		
		
		if (this.curOffset == 0)
		{
			this.wind.setScrollEn(resp.events.total>5);
			this.wind.setScrollBar();
			
			if (wind_H>0)
				this.wind.setH(wind_H)
			else
				if (resp.events.total == 0)
					this.wind.setH(110)
				else
					this.wind.setH(500);
		}




		
		
		this.totalN = resp.events.total;
		this.newN = resp.events.new_count;
		log("newN = ["+this.newN+"]");
		this.setNumber(this.newN);

        if ((this.newN>0) && (this.curOffset==0))
            this.clearEvents();

		this.curOffset = resp.events.offset + resp.events.list.length;
		
		this.loadingBar.insertAfter(this.items[this.items.length-1]);
		if (this.curOffset >= this.totalN)
			this.loadingBar.css({ display : 'none'});
		
		//no notificationsthis.loadingBar
		/*
		if (this.totalN  == 0)
			this.noNotifInfo.style.display = 'block'
		else
			this.noNotifInfo.style.display = 'none';
			*/
        if (this.totalN == 0)
        {
            $(this.itemsCanvas).append(this.templateEmpty);
        }
			
			
		//clear new events if there is any

			
			
		//WHP.resetH();
		WHP.controller.setTitle();
		
	},
	//error callback
	onError : function (e)
	{
		this.loadingBar.css({ display : 'none'});
		this.loading = false;
		log("WHP/notifications : Error while loading actual data! : "+e);
	},	
	getEventElem : function (_resp)
	{
		var nameLen = 30;
		var textBodyLen = 54;

		if (_resp.type == 1)
		{
			//log("_resp.type.val = ["+_resp.type.val+"] ["+(_resp.type.val==1)+"] ["+(_resp.type.val=='1')+"]");
            var element_div = this.templateLike.clone();
			element_div.image_id = _resp.id;
			var title = element_div.find( ".notifications_tittle" ).get()[0];
			title.innerHTML = getNameCutted(_resp.user.name, nameLen);

			var userLink = WHP.links.getUserProfileLink ( _resp.user.id );
			title.href = userLink;




			var image = element_div.find( ".notifications_image" ).get()[0];
			image.src = _resp.photo['i106x106'];
			element_div.wrapper = element_div.find( ".notifications_wrapper" ).get()[0];
			var timestamp = element_div.find( ".notifications_time" );
			timestamp.text(getTimeFormated(parseInt(_resp.date)*1000));





			image.linkObject = element_div.find( ".notifications_link").get()[0];
			var linkUrl = WHP.links.getPhotoLink(_resp.photo.id);
			image.linkObject.href = linkUrl;


		}else if (_resp.type == 2)
		{
			var element_div = this.templateComment.clone();
			element_div.image_id = _resp.id;

            var title = element_div.find( ".notifications_text" );

            $(title[0]).html("<a href='"+WHP.links.getUserProfileLink(_resp.user.id)+"' class='notifications_tittle'>"+getNameCutted(_resp.user.name, nameLen)+"</a> said");

            $(title[1]).html(getTextCutted(_resp.val, textBodyLen));

			var image = element_div.find( ".notifications_image" ).get()[0];
			image.src = _resp.photo['i106x106'];
			element_div.wrapper = element_div.find( ".notifications_wrapper" ).get()[0];
			var timestamp = element_div.find( ".notifications_time" );
			timestamp.text(getTimeFormated(parseInt(_resp.date)*1000));


			image.linkObject = element_div.find( ".notifications_link").get()[0];
			var linkUrl = WHP.links.getPhotoLink(_resp.photo.id);
			image.linkObject.href = linkUrl;

		}else if (_resp.type == 3)
		{
			var element_div = this.templateFollow.clone();
			element_div.image_id = _resp.id;
			var image = element_div.find( ".notifications_tittle" ).get()[0];

			image.innerHTML = getNameCutted(_resp.user.name, nameLen)+"<br/>";

            $(image).attr("href", WHP.links.getUserProfileLink(_resp.user.id));

			element_div.wrapper = element_div.find( ".notifications_wrapper" ).get()[0];
			var timestamp = element_div.find( ".notifications_time" );
			timestamp.text(getTimeFormated(parseInt(_resp.date)*1000));

			image.linkObject = element_div.find( ".notifications_link").get()[0];
			var userLink = WHP.links.getUserProfileLink ( _resp.user.id );
			image.linkObject.href = userLink;

		}else if (_resp.type == 5)
        {
            var element_div = this.templateComment.clone();
            element_div.image_id = _resp.id;

            var title = element_div.find( ".notifications_text" );

            $(title[0]).html("<a href='"+WHP.links.getUserProfileLink(_resp.user.id)+"' class='notifications_tittle'>"+getNameCutted(_resp.user.name, nameLen)+"</a> replied");

            $(title[1]).html(getTextCutted(_resp.val, textBodyLen));

            if (_resp.photo)
            {

                element_div.wrapper = element_div.find( ".notifications_wrapper" ).get()[0];
                var timestamp = element_div.find( ".notifications_time" );
                timestamp.text(getTimeFormated(parseInt(_resp.date)*1000));
                var image = element_div.find( ".notifications_image" ).get()[0];
                image.src = _resp.photo['i106x106'];
                image.linkObject = element_div.find( ".notifications_link").get()[0];
                var linkUrl = WHP.links.getPhotoLink(_resp.photo.id);
                image.linkObject.href = linkUrl;
            }
        }



        if (_resp.is_new)
        {
            element_div.css({ 'background-color' : '#e0e0e0' });
            timestamp.css({ 'color' : '#b7b7b7' });
        }

        addIntelloLinks(element_div);

        return element_div;
	},
	









	//update events
	startLPUpdate : function (e)
	{
		if ( WHP.auth.status )
		{
			$.ajax({
			  url: WHP.netcalls.lpCall,
			  data : { uid : WHP.auth.status.id, r :  Math.random(), token : WHP.auth.status.token },
			  timeout : this.LPtimerTimeout,
			  success: bind(this.LPcallback, this),
			  error: bind(this.LPcallbackErr, this)
			});
		}
	},
	LPcallback : function (response, status, xhr)
	{
        var resp = getObjectJson(response);
        if (!resp)
        {
            this.startLPTimer();
            return false;
        }
        this.loadNotifications(true);

        return false;

		if ((typeof(resp.list)=="undefined") || (!resp.list))
        {
            this.startLPTimer();
            return false;
        }


		if (resp.error)
		{
			log("WHP/notifications : error while loading page data!");
			if (!WHP.errors.hasNetError(resp))
			{
				WHP.notifications.LPcallbackErr();
			}
			return false;
		}

		
		this.wind.calculateScrollParams();
		var cH = this.wind.scrollParams.canvasH;
		var wH = this.wind.scrollParams.windH;
		var dY = this.wind.scrollParams.dY;
		
		
		var H = 0;
		for (var i=0; i<resp.list.length; i++)
		{
			var elem = this.getEventElem(resp.list[i]);
			//from top to bottom

			if (this.items.length>0)
				elem.insertBefore(this.items[0])
            else
                $(this.itemsCanvas).append(elem);

			H = H + elem[0].offsetHeight;
			this.items.splice(i,0,elem);
		}
		
		
		
		
		this.totalN = this.totalN + resp.list.length;
		this.wind.setScrollEn(this.totalN>5);
		this.wind.setScrollBar();
		
		this.newN = this.newN + resp.list.length;
		WHP.controller.setTitle();
		this.setNumber(this.newN);
		this.curOffset = this.curOffset + resp.list.length;
		this.setNotifyPos();
		
		//scroll positions
        var tmpH = this.wind.scrollParams.canvasH;
        var tmpY = this.wind.scrollParams.dY;

		this.wind.calculateScrollParams();

		var delt = this.wind.scrollParams.canvasH - tmpH;
		var pos = -(tmpY+delt)/this.wind.scrollParams.canvasH;



		//pos = pos - H/canvasH;	
		pos = Math.min(0, pos);
		pos = Math.max(-1, pos);



		this.wind.scrollWindowTo(pos);		
		
		this.startLPTimer();
	},
	LPcallbackErr : function (response)
	{		
		var status = response['status'];

		if (status != 0)
		{
			if (this.LPtimerAdapt==1)
				this.LPtimerAdapt = 2
			else
				this.LPtimerAdapt = this.LPtimerAdapt*this.LPtimerAdapt;
		}else{
			this.LPtimerAdapt = 1;
		}
		this.startLPTimer();
	},
	
	setNumber : function (_N)
	{
		WHP.menu.setNotifyNumber(_N);
	},
	
	//timer events
	startLPTimer : function ()
	{
		if (this.LPtimer != -1)
			clearInterval(this.LPtimer);
		this.LPtimer = setInterval(bind(this.LPTimercallback, this), this.LPtimerAdapt*this.LPtimerDelay);
	},
	LPTimercallback : function ()
	{
		this.startLPUpdate();
		clearInterval(this.LPtimer);
		this.LPtimer = -1;
	},
	stopLPTimer : function ()
	{
		if (this.LPtimer != -1)
			clearInterval(this.LPtimer);		
	},
	
	
	onLogOut : function ()
	{
		this.stopLPTimer();
		//this.windCont.style.display = "none";	
		this.hide();
		this.loading = false;
		this.curOffset = 0;
		this.newN = 0;
		this.totalN = 0;
		this.setNumber(0);
	}
}



WHP.download = {
	
	
	inited : false,
	
	wind : null, 
	windCont : null,


    stdTemplate : null,
    newTemplate : null,
    infoLoaded : false,

    labels : null,

	
	visible : false,
    showNew : false,

    hideMessage : true,
    curVersion : "",
    newVersion : "",

    coockieNameMessage : "download_hidemessage",
    coockieNameVersion : "download_curversion",

	//init function
	init: function ()
	{
        var not_show = getCookie(this.coockieNameMessage);

        if (not_show == null)
        {
            not_show = false;
        }else{
            not_show = (not_show == "true");
        }

        setCookie(this.coockieNameMessage, not_show, 365);
        this.hideMessage = not_show;
        if (this.hideMessage)
        {
            log("HIDE BUTTONS");
            WHP.menu.downloadButtons.css({display : 'none'});
        }





		this.wind = new whp_window_proto();
        this.wind.clearOnShow = false;
		this.windCont = id$('download_window');
		this.wind.init(this.windCont);

        this.stdTemplate = $("#download_standart");
        var links = this.stdTemplate.find(".download_directlink");
        links.click(bind(this.closeWindowOnClick, this));
        links.click(function() { WHP.stats.trackDownload("DOWNLOAD_WINDOW_STD"); });
        addIntelloLinks(this.stdTemplate);
        this.stdTemplate.checkBox = this.stdTemplate.find(".gui_checkmark_0");
        this.stdTemplate.checkBoxLabel = this.stdTemplate.find(".check_label");
        setCheckBox(this.stdTemplate.checkBox, bind(this.setCheckBox, this), this.stdTemplate.checkBoxLabel);

        this.newTemplate = $("#download_new");
        var links = this.newTemplate.find(".download_directlink");
        links.click(bind(this.closeWindowOnClick, this));
        links.click(function() { WHP.stats.trackDownload("DOWNLOAD_WINDOW_NEW"); });
        addIntelloLinks(this.newTemplate);
        this.newTemplate.changelogCont = this.newTemplate.find(".download_changelog_container");


        this.labels = $(WHP.menu.panelMenu).find(".controls_download_button");
        $(this.wind.itemsCanvas).append( this.stdTemplate );
		this.inited = true;
	},

    closeWindowOnClick : function(e)
    {
        log("close");
        if (this.wind.visible)
            this.wind.hide();
    },

    setCheckBox : function(_bool)
    {
        log("Bool = ["+_bool+"]");
        this.hideMessage = _bool;

        if (this.hideMessage)
        {
            WHP.menu.downloadButtons.css({ display : 'none'});
        }else{
            WHP.menu.downloadButtons.css({ display : ''});
        }
        setCookie(this.coockieNameMessage,  this.hideMessage, 365);
    },

    checkVersions: function()
    {
        if (this.infoLoaded)
            return false;

		//alert(WHP.netcalls.versionCall);
        $.ajax({
            url: WHP.netcalls.versionCall,
            data : { r : Math.random() },
            timeout : WHP.netTimeOut,
            success: bind(this.onCheckData, this),
            error: bind(this.onCheckDataErr, this)
        });
    },



    onCheckData: function(response)
    {
        var resp = getObjectJson(response);
        if (resp.error)
        {
            log("WHP/download : error while loading page data!");
            WHP.errors.hasNetError(resp);
            return false;
        }

        this.newVersion = resp.version.ios.available;
        var curVer = getCookie(this.coockieNameVersion);
        if (curVer == null)
        {
            curVer = this.newVersion;
        }



        this.curVersion = curVer;
        setCookie(this.coockieNameVersion, this.curVersion, 365);


        this.showNew = (this.curVersion != this.newVersion);

        log("["+this.showNew+"] new = ["+this.newVersion+"] ["+this.curVersion+"]");

        if (this.showNew)
        {
            log("SHOW NEW!");
            this.stdTemplate.remove();
            $(this.wind.itemsCanvas).append( this.newTemplate );


            var str = "";
            for (var i=0; i<resp.version.ios.changelog.length;i ++)
            {
                str = str + resp.version.ios.changelog[i];
            }
            str = str.replace(/(\r\n|\n|\r)/gm, "<br>");
            this.newTemplate.changelogCont.html(str);

            this.labels.removeClass().addClass("controls_download_button_new");

            if (!this.showMessage)
            {
                WHP.menu.downloadButtons.css({ display : ''});
            }
        }

        this.infoLoaded = true;

        var h = $(this.wind.itemsCanvas).height();

        if (this.wind.visible)
            this.wind.setH(h+1);
    },

    onCheckDataErr: function(response)
    {
        var status = response['status'];
        log("WHP/download : error status = ["+status+"]");
        this.infoLoaded = true;
    },
	
	show: function ()
	{
        if (this.showNew)
        {
            this.curVersion = this.newVersion;
            setCookie(this.coockieNameVersion, this.curVersion, 365);
        }

		this.wind.show();
        var h = $(this.wind.itemsCanvas).height();
        this.wind.setH(h+1);

        //WHP.resetH();
	},

	clickButton: function (_elem)
	{
        if (WHP.notifications.wind.visible)
            WHP.notifications.hide();


		if (!this.wind.visible)
        {
            var pos = $(_elem).offset();
            var posd = $(WHP.menu.panelMenu).offset();
            var w = $(_elem).width();
            var h = $(_elem).height();

            this.wind.setPos(pos.left-posd.left+w*0.5, pos.top-posd.top+h+9);

			this.show();
        }else
			this.hide();
	},

	hide: function ()
	{
		this.wind.hide();
	}
}



WHP.serviceMessages = {
	
	
	inited : false,
	mainObject : null,
    showMessage : false,

    downloadButton : null,

    timer : new Timer(1000/32, 18),
    heightH : 101,
    timerObject : {
        p0 : 0,
        p1 : 0,
        cP : 0
    },

	//init function
	init: function ()
	{
        //not [ X ] and authed user
        this.mainObject = $("#servicemessages");
        this.mainObject.closeButton = this.mainObject.find(".servicemessage_close");
        this.mainObject.closeButton.click(bind(this.closeButton, this));
        this.mainObject.donwloadButton = this.mainObject.find(".servicemessage_download");
        this.mainObject.donwloadButton.click( bind(this.clickDownload, this) );
        this.mainObject.donwloadButton.click(function() { WHP.stats.trackDownload("DOWNLOAD_SERVICE_MESSAGE") });

        this.timer.onTimerEvent = bind(this.timerEvent, this);

        /*
        if (this.showMessage)
            this.show();
            */

		this.inited = true;
	},

    clickDownload : function()
    {
        setCookie("hsdodl", "true", 60*100);
        this.hide();
    },

    onAuthChange : function()
    {
       if (this.showMessage)
       {
           setCookie("hsdodl", "true", 60*100);
           this.hide();
       }
    },

    checkVisible : function()
    {
        var photoDirect = true;
        if (WHP.controller.history.length>0)
            photoDirect = WHP.controller.history[0].url.indexOf("photo/")>-1;

        this.showMessage = (!(getCookie("hsdodl") == "true") && (WHP.auth.status == null) && photoDirect);

        if (this.mainObject == null)
            return false;


        //only on photo
        if (WHP.controller.curPage.urlStr == "photo")
        {
            if (WHP.controller.visible)
            if (this.showMessage)
            {
                WHP.stats.trackPhotoPlateShow();
                this.show();
            }
        }else{
            this.mainObject.css({ display:'none'});
        }
    },

    show : function()
    {
        this.mainObject.css({ display:''});
        this.timerObject.cP = 1.0;
        this.timerObject.p1 = 1.0;
    },

    hide: function()
    {
        this.timerObject.p0 = this.timerObject.cP;
        this.timerObject.p1 = 0;
        this.timer.reset();
        this.timer.start();
    },

    closeButton : function(e)
    {
        WHP.stats.trackXclick();
        setCookie("hsdodl", "true", 60*100);
        this.hide();
    },

    timerEvent : function(e)
    {
        var A = e.currentCount/e.repeatCount;
        var B = (Math.sin(Math.PI*(A-0.5))+1)*0.5;

        this.timerObject.cP = (1-A)*this.timerObject.p0 + A*this.timerObject.p1;
        var D = this.timerObject.cP;

        var C1 = 0.7;
        var C2 = 0.7;
        var A1 = Math.max(0, Math.min(1.0, D/C1));
        var A2 = Math.max(0, Math.min(1.0, (D-C2)/(1-C2)));

        A1 =  (Math.sin(Math.PI*(A1-0.5))+1)*0.5;
        A2 =  (Math.sin(Math.PI*(A2-0.5))+1)*0.5;

        setAlpha(this.mainObject, A2);
        this.heightH = 101*A1;
        this.mainObject.css({ height : this.heightH +'px'});

        if (A==1.0)
        if (this.timerObject.cP == 0)
        {
            this.showMessage = false;
            this.mainObject.css({ display:'none'});
        }
    }

}





WHP.timelineMessages = {
    inited : false,
    mainObject : null,
    showMessage : false,

    heightH : 0,
    heightH2 : 512,
    timer : new Timer(1000/32, 18),
    timer2 : new Timer(1000/32, 18),

    timerObject : {
        p0 : 0,
        p1 : 0,
        cP : 0
    },


    whyButton : null,
    tryButton1 : null,
    tryButton2 : null,

    desclaimer : null,

    likesCounter : 0,
    commentsCounter : 0,


    //init function
    init: function ()
    {
        //not [ X ] and authed user
        this.mainObject = $("#ogmessage");
        this.mainObject.closeButton = this.mainObject.find(".servicemessage_close");
        this.mainObject.closeButton.click(bind(this.closeButton, this));

        this.whyButton = this.mainObject.find(".why_button");
        this.whyButton.click(bind(this.onWhy, this));
        this.tryButton1 = this.mainObject.find(".ogmessage_try");
        this.tryButton2 = this.mainObject.find(".ogmessage_tryout");

        this.tryButton1.click(bind(this.getOG, this));
        this.tryButton2.click(bind(this.getOG, this));

        this.desclaimer = $(this.mainObject.find(".servicemessage_body")[1]);


        this.timer.onTimerEvent = bind(this.timerEvent, this);
        this.inited = true;
    },


    onAuthChange : function(_t)
    {

    },

    getOG : function()
    {
        FB.api('/me', function(e){ log(e);});
        WHP.auth.FB.loginOG(null, bind(this.onFBcall, this));
    },

    onFBcall: function (e)
    {
        WHP.pages.settings.linker.FB.onLink = bind( this.afterLink, this);
        WHP.pages.settings.linker.FB.showErrMsg = bind(WHP.popup_message.showAlert,WHP.popup_message);
        WHP.pages.settings.linker.FB.linkFb();
    },

    afterLink : function(resp)
    {
        log("AFTERLINK");
        log(resp);
        this.hide();
    },


    onGetSurePermission : function(e)
    {
       if (!e.data[0].publish_actions)
       {
           log("No opengraph access");

       }else{
           log("Opengraph access");
           this.hide();
           WHP.settings.useOpenGraph = true;
           WHP.pages.settings.setSettings();
       }
    },


    checkVisible : function()
    {
        var showWindow = !(getCookie("whp_stogw") == "true");
        var authStatus = WHP.auth.status;
        var OGStatus = WHP.settings.useOpenGraph;
        var cp = WHP.controller.curPage.urlStr;
        var registrationPages = (cp == WHP.pages.getstarted.urlStr) || (cp == WHP.pages.findfriends.urlStr);


        var commentsC =  WHP.stats.getCommentsCount();
        var likesC = WHP.stats.getLikesCount();
        var sharesC = WHP.stats.getSharesCount();

        if ((likesC == 100) || (commentsC == 20) || (sharesC == 5)|| (sharesC == 25))
        {
            if (!showWindow)
            {
                //set parameter more
                //!!!

                log("Make Show window on trigger!");
                this.timerObject.cP = 1.0;
                setCookie("whp_stogw", "false", 60*1000);
                showWindow = true;
            }
        }

        this.showMessage = showWindow && authStatus && !OGStatus && !registrationPages;
        if (this.mainObject == null)
            return false;

        if (this.showMessage)
        {
            //only on photo
            this.show();
            this.hide2();
        }else{
            if (this.mainObject.css("display") != "none")
                this.mainObject.css({ display:'none'});
        }
    },

    onWhy : function()
    {
        this.desclaimer.css({ height : ""});
    },

    hide2 : function()
    {
        this.desclaimer.css({ height : "0px"});
    },

    show : function()
    {
        if (this.timerObject.cP==1.0)
        {
            if (this.mainObject.css("display") == "none")
                this.mainObject.css({ display:''});

            return false;
        }

        this.mainObject.css({ display:''});
        this.timerObject.cP = 1.0;
        this.timerObject.p1 = 1.0;
    },

    hide: function()
    {
        if (this.timerObject.cP==0.0)
            return false;

        this.timerObject.p0 = this.timerObject.cP;
        this.timerObject.p1 = 0;
        this.timer.reset();
        this.timer.start();

        setCookie("whp_stogw", "true", 60*1000);
    },

    closeButton : function(e)
    {
        this.hide();
    },

    timerEvent : function(e)
    {
        var A = e.currentCount/e.repeatCount;
        var B = (Math.sin(Math.PI*(A-0.5))+1)*0.5;

        this.timerObject.cP = (1-A)*this.timerObject.p0 + A*this.timerObject.p1;
        var D = this.timerObject.cP;

        var C1 = 0.7;
        var C2 = 0.7;
        var A1 = Math.max(0, Math.min(1.0, D/C1));
        var A2 = Math.max(0, Math.min(1.0, (D-C2)/(1-C2)));

        A1 =  (Math.sin(Math.PI*(A1-0.5))+1)*0.5;
        A2 =  (Math.sin(Math.PI*(A2-0.5))+1)*0.5;

        setAlpha(this.mainObject, A2);
        this.heightH = this.mainObject.outerHeight()*A1;
        this.mainObject.css({ height : this.heightH +'px'});

        if (A==1.0)
        if (this.timerObject.cP == 0)
        {
            this.showMessage = false;
            this.mainObject.css({ display:'none'});
        }
    }

}

